Is there a "word wrap" property for JLabel?

I am displaying some text in a JLabel. Basically I am generating that text dynamically, and then I apply some HTML tags (eg, BR and B ) to format the text. Finally I assign this formatted text to my JLabel.

Now I want my Jlabel to automatically wrap the text to the next line when it reaches the end of screen, like the "Word Wrap" feature in Note Pad.

How can I do that?


Should work if you wrap the text in <html>...</html>

UPDATE: You should probably set maximum size, too, then.


A width can be set for the body using HTML styles (CSS). This in turn will determine the number of lines to render and, from that, the preferred height of the label.

Setting the width in CSS avoids the need to compute where line breaks should occur in (or the best size of) the label.

import javax.swing.*;

public class FixedWidthLabel {

    public static void main(String[] srgs) {
        final String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla urna. Donec sit amet risus nisl, a porta enim. Quisque luctus, ligula eu scelerisque gravida, tellus quam vestibulum urna, ut aliquet sapien purus sed erat. Pellentesque consequat vehicula magna, eu aliquam magna interdum porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sollicitudin sapien non leo tempus lobortis. Morbi semper auctor ipsum, a semper quam elementum a. Aliquam eget sem metus.";
        final String html1 = "<html><body style='width: ";
        final String html2 = "px'>";

        Runnable r = new Runnable() {

            @Override
            public void run() {
                JOptionPane.showMessageDialog(
                        null, new JLabel(html1 + "200" + html2 + s));
                JOptionPane.showMessageDialog(
                        null, new JLabel(html1 + "300" + html2 + s));
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

在这里输入图像描述在这里输入图像描述


One way would be to use a JTextArea instead of a JLabel with setWrapStyleWord and setLineWrap set to true and with settings to make it look and behave like a JLabel (remove the border, make it non-opaque, make it non-editable and non-focusable).

Otherwise if you absolutely need to use a JLabel , you'd be forced to use FontMetrics to measure your text, check for white-space, and then add the HTML hard-breaks in the appropriate positions yourself.

链接地址: http://www.djcxy.com/p/88884.html

上一篇: 没有可以访问Foo类型的封闭实例

下一篇: 是否有JLabel的“自动换行”属性?