New line at JLabel

How can I display a new line in JLabel ?

For example, if I wanted to:

Hello World!
blahblahblah

Here is what I have right now:

 JLabel l = new JLabel("Hello World!\nblahblahblah", SwingConstants.CENTER); 

This is what is displayed:

Hello World! blahblahblah

Forgive me if this is a stupid question, I'm just learning some Swing basics ...

+78
java user-interface formatting swing jlabel
Jul 07 '09 at 2:28
source share
6 answers

Surround the string with <html></html> and break the string with <br/> .

 JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER); 
+135
Jul 07 '09 at 2:33
source share

You can use the MultilineLabel component in Jide Open Source Components.

http://www.jidesoft.com/products/oss.htm

+2
Jul 07 '09 at 7:43
source share

You can do

 JLabel l = new JLabel("<html><p>Hello World! blah blah blah</p></html>", SwingConstants.CENTER); 

and it will automatically pack it if necessary.

+2
Feb 08 '11 at 13:10
source share

Thanks to Aakash for recommending JIDE's MultipleineLabel. Recently, JIDE StyledLabel has also improved multi-line support. I would recommend it over MultilineLabel, as it has many other great features. You can check out the article on StyledLabel below. It is still free and open source.

http://www.jidesoft.com/articles/StyledLabel.pdf

+2
Nov 04 '11 at 15:56
source share

You can try:

 myLabel.setText("<html>" + myString.replaceAll("<","&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br/>") + "</html>") 

The advantages of this:

  • It replaces all newline characters <br/> , without fail.
  • It automatically replaces the possible < and > with &lt; and &gt; accordingly, preventing chaos of transfer.

What does he do:

  • "<html>" + adds an opening html tag at the beginning
  • .replaceAll("<", "&lt;").replaceAll(">", "&gt;") < and > for convenience
  • .replaceAll("\n", "<br/>") replaces all newlines with br (HTML break break) tags for what you want.
  • ... and + "</html>" closes our html tag at the end.

PS: I'm sorry to wake up such an old post, but whatever you have, you have a reliable snippet for your Java!

+2
Apr 23 '16 at 19:10
source share

JLabel is actually capable of displaying some elementary HTML code, so it does not respond to the use of a newline character (unlike, say, System.out).

If you put the appropriate HTML and use <BR> , you will get your new lines.

+1
Jul 07 '09 at 2:39
source share



All Articles