views:

607

answers:

4

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);  
    }
+8  A: 

Use HTML in setText, e.g.

myLabel.setText("<html><body>with<br>linebreak</body></html>");
ammoQ
+4  A: 

You can put HTML inside of a JLabel and use the linebreak tag to achieve this.

Amir Afghani
+3  A: 

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.

As suggested you can use HTML to enable line wrapping. However, I've actually created a custom Swing UI delegate not long ago to achieve this and even more: MultiLineLabelUI.

It will wrap your text to fit the available space and also respect hard line breaks. If you choose to try it out, it is as simple as:

JLabel label = new JLabel("Text that'll wrap if necessary");
label.setUI(MultiLineLabelUI.labelUI);

Or alternatively use the custom MultiLineLabel class that in addition to wrapping text supports vertical and horizontal text alignment.

Samuel Sjöberg
A: 

What about using the wrapping feature in a JTextArea?

    String text = "some really long string that might need to"+
                  "be wrapped if the window is not wide enough";

    JTextArea multi = new JTextArea(text);
    multi.setWrapStyleWord(true);
    multi.setLineWrap(true);
    multi.setEditable(false);

    JLabel single = new JLabel(text);

    JPanel textpanel = new JPanel(new GridLayout(2,1));
    textpanel.add(multi);
    textpanel.add(single);

    JFrame frame = new JFrame();
    frame.add(textpanel);
    frame.pack();
    frame.setVisible(true);
Stew