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); }
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.
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.
\r\n is the correct way to do it in Windows for example.
Use HTML in setText, e.g.
myLabel.setText("<html><body>with<br>linebreak</body></html>");
You can get automatic line break if you set the paragraph width in html.
label.setText("<html><p style=\"width:100px\">"+paragraph+"</p></html>");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With