Question
How can I make the text of a JLabel extend onto another line?
Solution
You can do it by putting HTML in the code, so:
JFrame frame = new JFrame();
frame.setLayout(new GridLayout());
JLabel label = new JLabel("<html>First line<br>Second line</html>");
frame.add(label);
frame.pack();
frame.setVisible(true);
OTHER TIPS
if you want your jLabel Text to resize automaticly for example in a stretchable gridbaglayout its enough just to put its text in html tags like so:
JLabel label = new JLabel("<html>First line and maybe second line</html>");
Type the content (i.e., the "text" property field) inside a <html></html>
tag. So you can use <br>
or<P>
to insert a newline.
For example:
String labelContent = "<html>Twinkle, twinkle, little star,<BR>How I wonder what you are.<BR>Up above the world so high,<BR>Like a diamond in the sky.</html>";
It will display as follows:
Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
You can also use a JXLabel from the SwingX library.
JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);
I have used JTextArea for multiline JLabels.
JTextArea textarea = new JTextArea ("1\n2\n3\n"+"4\n");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html
In my case it was enough to split the text at every \n
and then create a JLabel
for every line:
JPanel panel = new JPanel(new GridLayout(0,1));
String[] lines = message.split("\n");
for (String line : lines) {
JLabel label = new JLabel(line);
panel.add(label);
}
I used above in a JOptionPane.showMessageDialog
It is possible to use (basic) CSS in the HTML.
This question was linked from Multiline JLabels - Java.
String labelText ="<html>Name :"+name+"<br>Surname :"+surname+"<br>Gender :"+gender+"</html>";
JLabel label=new JLabel(labelText);
label.setVisible(true);
label.setBounds(10, 10,300, 100);
dialog.add(label);
why you are giving complex things...you can just do it by putting "\n" instead of html tags