Java: Linebreaks in JLabels?

52,810

Solution 1

Use HTML in setText, e.g.

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

Solution 2

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

  label.setText("<html><p style=\"width:100px\">"+paragraph+"</p></html>");

Solution 3

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.

UPDATE

I lost the domain with the original code samples. It can now be viewed on github instead: https://github.com/sasjo/multiline

Solution 4

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

Solution 5

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);
Share:
52,810
Nick Heiner
Author by

Nick Heiner

JS enthusiast by day, horse mask enthusiast by night. Talks I've Done

Updated on November 11, 2021

Comments

  • Nick Heiner
    Nick Heiner over 2 years

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