0

I have JLabel that displays a dynamic text. This text can be very long or short. I want to wrap text and I'm trying it this way:

    panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
    panel1.setMaximumSize(new Dimension(500, 150));
    ....
    lblInfo=new JLabel();
    lblInfo.setText("<html><b>Q: "+ infoObj.getText()+"</b></html>");
    ...
    panel1.add(lblInfo);

But this doesn't seem to work. When a long text comes, this JLabel just goes out of the screen (beyond the size of my panel) and I can only see the end of it.

I found some solutions on Stack Overflow using JTextField instead of label. But due to some requirements in my project, I have to use JLabel itself in my case.

double-beep
  • 5,031
  • 17
  • 33
  • 41
developer3
  • 75
  • 2
  • 9

1 Answers1

3

When a long text comes, this JLabel just goes out of the screen

Yes, the text will only wrap when you have a <br> in the actual text. The <br> at the start of the text does nothing.

I found some solutions on stackoverflow using JTextField instead of label

I doubt that. A JTextField ALWAYS displays text on a single line.

The suggestion you will find in the forum is to use a JTextArea with wrapping:

JTextArea textArea = new JTextArea(5, 20);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
Frakcool
  • 10,915
  • 9
  • 50
  • 89
camickr
  • 321,443
  • 19
  • 166
  • 288
  • *"the text will only wrap when you have a `
    ` in the actual text. The `
    ` at the start of the text does nothing."* 1) The OP is using the mark-up for bold, not break. 2) Break is neither the only, nor the best, way to wrap HTML text. (A CSS width is better.)
    – Andrew Thompson Nov 25 '16 at 23:31
  • @Andrew yes I made the text bold. If I'm to add
    to wrap text in JLabel, I have to do it in between my dynamically obtained text. So what's the the other option? I tried setting the size of JLabel. But when the text is very long, it just overflows the size and does not wrap.
    – developer3 Nov 27 '16 at 18:30
  • *"So what's the the other option?"* Setting the width of the body of the HTML using CSS. See an example linked from [this answer](http://stackoverflow.com/a/14011645/418556). – Andrew Thompson Nov 27 '16 at 19:17