8

I want to display some text in JLabel at runtime. I just want to know that is there anyway through which the text is displayed on multiple lines. For example, I want my text to be displayed in following format:

Line 1
Line 2
Line 3

String  sText  = "Line1 \n Line2 \n Line3";
jLabel1.setText (sText);

I tried the above code but its not working. Am I doing some thing wrong or does JLabel not support said feature?

If I'm unable to achieve the above functionality, how can I add multiple labels (one for each line) in JPanel at runtime?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jame
  • 21,150
  • 37
  • 80
  • 107
  • 2
    The other option is to use single line JLabels but place them in a JPanel (the container) that uses a layout that allows you to stack the JLabels, such as a GridLayout or a BoxLayout. – Hovercraft Full Of Eels Sep 16 '11 at 16:31

3 Answers3

16

JLabel supports HTML. You can write:

String  sText  = "<html>Line1 <br/> Line2 <br/> Line3</html>";
jLabel1.setText (sText);

Edit: I added back slashes with br tag in order to make code working

Jame
  • 21,150
  • 37
  • 80
  • 107
Chandra Patni
  • 17,347
  • 10
  • 55
  • 65
5

use <br> instead of using \n and prefix it by <html> like this

"<html>Line1 <br> Line2 <br> Line3</html>";
confucius
  • 13,127
  • 10
  • 47
  • 66
4

A better option for HTML formatted text in this case, is to drop the hard line breaks (except at the end of paragraphs) and set the width of the HTML using CSS.

As seen in the 2nd example (LabelRenderTest.java) shown here.

JLabel with multiline, formatted, text.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433