Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any MultiLine JLabel exist?

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?

like image 780
Jame Avatar asked Sep 16 '11 16:09

Jame


People also ask

How do I get JLabel to text next line?

Surround the string with <html></html> and break the lines with <br/> . just a little correction: use <br /> instead of just <br> ... this is recommended way of doing it (to not miss any closing tags)...

What is the difference between JLabel and JPanel?

by giving the JLabel constructor the String argument that is the text to describe what's in there. A JPanel, on the other hand, is a Panel, a designated part of the GUI. Given that it is a distinct part, it is naturally a Container, and should thus be given the stuff.

How do you put a JLabel on top of another JLabel?

The short answer is yes, as a JLabel is a Container , so it can accept a Component (a JLabel is a subclass of Component ) to add into the JLabel by using the add method: JLabel outsideLabel = new JLabel("Hello"); JLabel insideLabel = new JLabel("World"); outsideLabel. add(insideLabel);

How do you change the width of a JLabel?

You can set a fixed the size by setting the minimum, preferred and maximum size: setMinimumSize(width, height); setPreferredSize(width, height); setMaximumSize(width, height);


3 Answers

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

like image 186
Chandra Patni Avatar answered Oct 19 '22 15:10

Chandra Patni


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

"<html>Line1 <br> Line2 <br> Line3</html>";
like image 31
confucius Avatar answered Oct 19 '22 14:10

confucius


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.

like image 35
Andrew Thompson Avatar answered Oct 19 '22 15:10

Andrew Thompson