0

I want my JLabel to be the height required for the particular string that is assigned to the text. The text string can can have any number of lines, which use the \n in the string. So if you have a string the "Hello\nit\nis\nme\n" the height of the label will automatically be adjusted to fit the 4 lines.

How to achieve that?

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
user565660
  • 1,121
  • 3
  • 17
  • 34

2 Answers2

2
  • Use proper JTextComponent rather than use HTML formatted text in the JLabel

  • I think that for "Hello\nit\nis\nme\n" should be disabled JTextArea right JComponent

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
mKorbel
  • 108,320
  • 17
  • 126
  • 296
2

A JLabel1 would typically ignore the new-line character. To get multi-line text, either use a mutli-line component such as a JTextArea2 or use HTML formatting in the label.

  1. Here is an example of using HTML formatting (screenshot above). The example uses styles (CSS) to cause the line breaks to be inserted automatically. This is much easier than calculating where to insert line-breaks in text blocks manually.
  2. Of course, a JTextArea having methods like setLineWrap(true) & setWrapStyleWord(true) also handles line wrap automatically.
Community
  • 1
  • 1
Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405