Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word Wrap in JButtons

Is it possible to achieve automatic word wrap of texts in JButtons? I am having few dynamic buttons which I create on runtime. I want to put word wrap feature on the buttons so that I can see some better test on buttons. Is it possible to do that?

like image 626
Deepak Avatar asked Apr 23 '11 18:04

Deepak


People also ask

What is word wrap in keyboard?

Word wrap may refer to any of the following: 1. Sometimes referred to as a run around and wrap around, word wrap is a feature in text editors and word processors. It moves the cursor to the next line when reaching the end without requiring you to press Enter .

What is word wrap example?

An example of word wrap is the automatic moving of the words on a long line of words to fit the words within a cell on a spreadsheet. (computing) A word processing feature which automatically adjusts lines of text to fit within the page margins. Words exceeding the margins are set to begin a new line.


1 Answers

This example uses Java's inbuilt CSS rendering abilities to to do the 'heavy lifting' of determining when to do a line break. It uses a JLabel, but the same principles apply to any component that will render HTML.

FixedWidthText.java

import javax.swing.*;

class FixedWidthText {

    public static void showLabel(int width, String units) {
        String content1 = "<html>"
                + "<body style='background-color: white; width: ";
        String content2 = "'>"
                + "<h1>Fixed Width</h1>"
                + "<p>Body width fixed at ";
        String content3
                = " using CSS.  "
                + "Java's HTML"
                + " support includes support"
                + " for basic CSS.</p>";
        final String content = content1 + width + units
                + content2 + width + units + content3;
        Runnable r = () -> {
            JLabel label = new JLabel(content);
            JOptionPane.showMessageDialog(null, label);
        };
        SwingUtilities.invokeLater(r);
    }

    public static void main(String[] args) {
        showLabel(160, "px");
        showLabel(200, "px");
        showLabel(50, "%");
    }
}

Screen shots

160px

enter image description here

200px

enter image description here

50%

enter image description here

like image 90
Andrew Thompson Avatar answered Oct 21 '22 04:10

Andrew Thompson