views:

585

answers:

6

Hi,

I want to do this:

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

Currently this results in a label that displays

This isa multi-line string

I want it to do this instead:

This is
a multi-line string

Any suggestions?

Thank you


EDIT: Implemented solution

In body of method:

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

Helper method:

public static String convertToMultiline(String orig)
{
    return "<html>" + orig.replaceAll("\n", "<br>");
}
+1  A: 

JLabel can accept html code. Maybe you can try to use the "< b r >" tag.

Example: JLabel myLabel = new JLabel(); myLabel.setText(" This is a < b r > multi-line string ");

I don't have the JDK with me right now, So I am not 100% confirm with the solution, but you can give it a shot.

p.s. Please remove the whitespace between the < and b and r and > when you try.

KWAN TOH CHOONG
+7  A: 

You can use HTML in JLabels. To use it, your text has to start with <html>.

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

See Swing Tutorial: JLabel and Multiline label (HTML) for more information.

Peter Lang
+1  A: 

The direct procedure of writing a multi-line text in a jlabel is:

JLabel label = new JLabel("<html>First Line<br>Second Line</html>"); 
Marco Schmid
A: 

Another easy way (but changes the text style a bit) is to use a <pre></pre> html block.

This will persist any formatting the user entered if the string you are using came from a user input box.

Example:

JLabel label = new JLabel("<html><pre>First Line\nSecond Line</pre></html>"); 
Austyn Mahoney
A: 

The problem with using html in JLabel or any Swing component is that you then have to style it as html, not with the usual setFont, setForeground, etc. If you're ok with that, fine.

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

Geoffrey Zheng