53

I am displaying some text in a JLabel. Basically I am generating that text dynamically, and then I apply some HTML tags (e.g., 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?

james.garriss
  • 11,468
  • 6
  • 75
  • 94
Jame
  • 18,248
  • 32
  • 76
  • 102
  • 4
    Just FYI, Andrew's answer is the best. – Hovercraft Full Of Eels Oct 22 '11 at 19:02
  • @HovercraftFullOfEels I just knew the screen shots would make the difference! – Andrew Thompson Oct 22 '11 at 19:06
  • 1
    Yeah, I've got to start doing that a bit more, but still it helps to have the right answer. I suppose I should learn a bit of HTML and styles... – Hovercraft Full Of Eels Oct 22 '11 at 19:11
  • @AndrewThompson They're pretty cool, but make you answer slower! :) – MarianP Oct 22 '11 at 19:20
  • 2
    @HovercraftFullOfEels +1 for the 2nd sentence, and not just you, but **any** server side developer using **any** language. It astounds me how little that (e.g.) servlet developers understand about the HTML their apps. are spewing out. As to the first.. some might consider my incessant addition of images to be visual 'noise'. – Andrew Thompson Oct 22 '11 at 19:22
  • @MarianP True, so I use a trick. Post the source 1st, then add the images in an edit. Of course, that didn't help here, since it took me longer to write the (v. short) source than it took for 2 answers and a tick. ;) – Andrew Thompson Oct 22 '11 at 19:25

7 Answers7

95

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 html = "<html><body style='width: %1spx'>%1s";

        Runnable r = () -> {
            JOptionPane.showMessageDialog(
                    null, String.format(html, 200, s));
            JOptionPane.showMessageDialog(
                    null, String.format(html, 300, s));
        };
        SwingUtilities.invokeLater(r);
    }
}

enter image description here enter image description here

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
  • 1
    Yeah, this one's the winner. :) – Hovercraft Full Of Eels Oct 22 '11 at 18:57
  • 11
    +1 and if you need to have a variable width label you can use use "100%" instead of "200px" (assuming your GUI uses an appropriate layout manager). – camickr Oct 22 '11 at 21:13
  • 3
    @SteveCohen If this were HTML for a browser, yes. This is merely HTML for Swing components and we can make many shortcuts. One advantage of this is that it allows us to (easily) dynamically add new content to the HTML. E.G. `label.setText( label.getText() + "
  • New list bullet" );`
  • – Andrew Thompson Mar 24 '12 at 15:41
  • @B1CL0PS *"..Is it still viable?.."* It sure is! If it fails for you, you are best off posting an [MCVE](http://stackoverflow.com/help/mcve) on your own question.. – Andrew Thompson Jan 12 '14 at 02:09
  • Just noticed that JLabel with in them look differently on Vista and 7 with native L&F: https://trello-attachments.s3.amazonaws.com/51b5f6a477d99db360005655/53995637865128f50782b410/1698x1314/315f89565f34cc9fa9d95f858e45e287/Screen_Shot_2014-06-12_at_11.26.14_AM.png – Ivan Nikitin Jun 14 '14 at 10:57
  • 3
    Remember that certain characters need to be escaped or turned into their HTML equivalents. – Chris Dennett Sep 08 '14 at 13:09
  • @ChrisDennett Yes you're right, something to be aware of and look out for. – Andrew Thompson Sep 08 '14 at 13:16