Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swing: Multiline labels? [duplicate]

Possible Duplicate:
Multiline text in JLabel

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>"); } 
like image 383
bguiz Avatar asked Jan 28 '10 06:01

bguiz


2 Answers

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.

like image 108
Peter Lang Avatar answered Oct 14 '22 17:10

Peter Lang


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 totally looks the same for me, but its ugly

like image 38
Whimusical Avatar answered Oct 14 '22 16:10

Whimusical