[java] Multiline text in JLabel

How can I make the text of a JLabel extend onto another line?

This question is related to java jlabel

The answer is


This is horrifying. All these answers suggesting adding to the start of the label text, and there is not one word in the Java 11 (or earlier) documentation for JLabel to suggest that the text of a label is handled differently if it happens to start with <html>. Who says that works everywhere and always will? And you can get big, big surprises wrapping arbitrary text in and handing it to an html layout engine.

I've upvoted the answer that suggests JTextArea. But I'll note that JTextArea isn't a drop-in replacement; by default it expands to fill rows, which is not how JLabel acts. I haven't come up with a solution to that yet.


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


You can also use a JXLabel from the SwingX library.

JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);

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.


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);

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


It is possible to use (basic) CSS in the HTML.


This question was linked from Multiline JLabels - Java.


You can use JTextArea and remove editing capabilities to get normal read-only multiline text.

JTextArea textArea = new JTextArea("line\nline\nline");
textArea.setEditable(false);

JTextArea

setEditable


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>");

why you are giving complex things...you can just do it by putting "\n" instead of html tags