Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Linebreaks in JLabels?

I'm trying to make a Swing JLabel with multiple lines of text. It's added just fine, but the line breaks don't come through. How do I do this? Alternatively, can I just specify a maximum width for a JLabel and know that the text would wrap, like in a div?

    private void addLegend() {         JPanel comparisonPanel = getComparisonPanel();          //this all displays on one line         JLabel legend = new JLabel("MMM FFF MMM FFFO O OOM   M MMMM.\nMMM FFF MMM FFFO O OOM   M MMMM.\nMMM FFF MMM FFFO O OOM   M MMMM.\n");           comparisonPanel.add(legend);             } 
like image 763
Nick Heiner Avatar asked Dec 03 '09 19:12

Nick Heiner


People also ask

How do you wrap text in JLabel?

As per @darren's answer, you simply need to wrap the string with <html> and </html> tags: myLabel. setText("<html>"+ myString +"</html>"); You do not need to hard-code any break tags.

How do you insert a line break in JLabel?

You can get automatic line break if you set the paragraph width in html. Show activity on this post. By default, Swing does not wrap text. If you specify a size on the JLabel it will only paint the part of the text that fits and then add "..." to the end.

How do you break a line in Java GUI?

\r\n is the correct way to do it in Windows for example.


2 Answers

Use HTML in setText, e.g.

myLabel.setText("<html><body>with<br>linebreak</body></html>"); 
like image 117
Erich Kitzmueller Avatar answered Sep 22 '22 09:09

Erich Kitzmueller


You can get automatic line break if you set the paragraph width in html.

  label.setText("<html><p style=\"width:100px\">"+paragraph+"</p></html>"); 
like image 43
sayem siam Avatar answered Sep 19 '22 09:09

sayem siam