Java swing: multi-line labels?

Possible duplicate:
Multi-line text in JLabel

I want to do this:

JLabel myLabel = new JLabel(); myLabel.setText("This is\na multi-line string"); 

This currently results in a label that displays

 This isa multi-line string 

I want him to do this instead:

 This is a multi-line string 

Any suggestions?

thank




EDIT: Implemented Solution

In the body of the method:

 myLabel.setText(convertToMultiline("This is\na multi-line string")); 

Helper Method:

 public static String convertToMultiline(String orig) { return "<html>" + orig.replaceAll("\n", "<br>"); } 
+50
java string multiline swing jlabel
Jan 28 '10 at 6:33
source share
7 answers

You can use HTML in JLabels . To use it, your text must begin with <html> .

Set the text to "<html>This is<br>a multi-line string" and it should work.

See Swing Tutorial: JLabel and Multi-Line Label (HTML) for more information.

+62
Jan 28
source share
 public class JMultilineLabel extends JTextArea{ private static final long serialVersionUID = 1L; public JMultilineLabel(String text){ super(text); setEditable(false); setCursor(null); setOpaque(false); setFocusable(false); setFont(UIManager.getFont("Label.font")); setWrapStyleWord(true); setLineWrap(true); //According to Mariana this might improve it setBorder(new EmptyBorder(5, 5, 5, 5)); setAlignmentY(JLabel.CENTER_ALIGNMENT); } } 

It looks the same to me, but it's terrible

+13
Jun 14 2018-12-12T00:
source share

Another easy way (but to slightly change the style of the text) is to use the <pre></pre> html block.

This will be saved in any formatting entered by the user if the line you are using leaves the user input window.

Example:

 JLabel label = new JLabel("<html><pre>First Line\nSecond Line</pre></html>"); 
+6
Sep 25 '10 at 2:00
source share

Direct procedure for writing multi-line text in jlabel:

 JLabel label = new JLabel("<html>First Line<br>Second Line</html>"); 
+5
Jan 28
source share

The problem with using html in JLabel or any Swing component is that you need to style it as html and not with the usual setFont , setForeground , etc. If you're okay with that, great.

Otherwise, you can use something like MultilineLabel from JIDE, which extends JTextArea . This is part of their open source Commom Layer .

+5
Sep 25 '10 at 19:30
source share

JLabel can accept HTML code. Maybe you can try using the <br> tag.

Example:

 JLabel myLabel = new JLabel(); myLabel.setText("<html> This is a <br> multi-line string </html>"); 
+3
Jan 28 '10 at 6:44
source share
+3
Jan 28 '10 at 8:36
source share



All Articles