Java: Linebreaks in JLabels?

Nick Heiner picture Nick Heiner · Dec 3, 2009 · Viewed 48k times · Source

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

Answer

Erich Kitzmueller picture Erich Kitzmueller · Dec 3, 2009

Use HTML in setText, e.g.

myLabel.setText("<html><body>with<br>linebreak</body></html>");