84

I have a JLabel which has a lot of text on it. Is there a way to make the JLabel have a max width so that it will wrap the text to make it not exceed this width?

Thanks

Aly
  • 15,865
  • 47
  • 119
  • 191

10 Answers10

64

No.

You can use HTML in the label, but then you must hard code the break tag.

A better approach is to use a JTextArea and turn wrapping on. You can change the background,foreground, font etc. of the text are to make it look like a label.

Note, this answer is outdated as of at least Java 7.

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. The text wraps as the component resizes.

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 15
    That's not entirely true. If using HTML you *can* hard code the break tags, but if you use HTML and assign the maximum size, the text will get wrapped automatically. – Daniel Rikowski Feb 14 '11 at 12:52
  • 2
    If you decide to hard code break tags, make sure you use
    and not
    , as Java 5 doesn't like the latter.
    – Craigo Aug 30 '11 at 01:19
  • i like the second idea because the first may break a word to half and what i want is word wrapping – shareef May 09 '15 at 07:53
  • 1
    *"You can use HTML in the label, but then you must hard code the break tag."* This is wrong. CSS can specify a preferred width, then the string will wrap on word, automatically, into as many lines as needed. – Andrew Thompson Jan 06 '17 at 11:23
50

Yes there are two similar ways (first with css style="width:...px", second with html WIDTH=.......:

1.

labelText = String.format("<html><div style=\"width:%dpx;\">%s</div></html>", width, text);

2.

labelText = String.format("<html><div WIDTH=%d>%s</div></html>", width, text);
matteoh
  • 2,810
  • 2
  • 29
  • 54
Alexander.Berg
  • 2,225
  • 1
  • 17
  • 18
  • 6
    The whole thing about using html to make text wrap feels like a hack, but it's the easiest way to make it work. Setting the size in the div is exactly what I needed to make the JLabel wrap with a maximum width without any 3rd party libraries or overly-complicated hacks. – Peter Dolberg Mar 26 '12 at 15:27
  • 7
    What if window size changes? Text has to be reflown according to new label width, but with this solution you would have to set it again. – Andrii Chernenko Nov 21 '13 at 00:40
  • 1
37

or simply use

myLabel.setText("<html>"+ myString +"</html>");
darren
  • 371
  • 3
  • 2
  • With JDK 7 that was sufficient, thanks! `JLabel lblTitle = new JLabel("My very very very long title text");` – Matthieu May 04 '13 at 05:58
  • 4
    If you do this, you should make sure any HTML entities in `myString` are first escaped. If `myString` is something like "Value < 5" it will appear as "Value 5". – Rangi Keen Nov 16 '15 at 17:58
13

You can use HTML without hard coding break tags if you use paragraph tags instead.

JLabel biglabel = new JLabel("<html><p>A lot of text to be wrapped</p></html>");
demBones
  • 155
  • 1
  • 5
11

JXLabel in the SwingX project supports wrapping

JXLabel label = new JXLabel(somelongtext);
label.setLineWrap(true);  
kleopatra
  • 51,061
  • 28
  • 99
  • 211
9

Other than wrapping the text in <html> tags, you also have to put the label into a container that respects the preferred height and sets the width to maximum. For example, you can put the label in to the NORTH of a BorderLayout.

Here is a simple but complete working program to illustrate this. You can resize the frame in any way you want; the label will occupy the whole width and the height will adjust accordingly to wrap the text. Notice that all that I'm doing is using <html> tags and putting the label in the NORTH of the BorderLayout.

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Dimension;

public class LabelWrap {

    public static JPanel createPanel() {
        JLabel label = new JLabel();
        label.setText("<html>"
            + "<h3>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h3>"
            + "<p>Duis a tincidunt urna. Phasellus tristique interdum mauris, "
            + "ut vestibulum purus suscipit eget. Aenean massa elit, accumsan "
            + "non faucibus vel, dictum placerat urna. In bibendum est sagittis "
            + "urna iaculis quis sagittis velit commodo. Cum sociis natoque "
            + "penatibus et magnis dis parturient montes, nascetur ridiculus "
            + "mus. Nam quis lacus mauris. Phasellus sem libero, convallis "
            + "mattis sagittis vel, auctor eget ipsum. Vivamus molestie semper "
            + "adipiscing. In ac neque quis elit suscipit pharetra. Nulla at "
            + "orci a tortor consequat consequat vitae sit amet elit. Praesent "
            + "commodo lacus a magna mattis vehicula. Curabitur a hendrerit "
            + "risus. Aliquam accumsan lorem quis orci lobortis malesuada.</p>"
            + "<p>Proin quis viverra ligula. Donec pulvinar, dui id facilisis "
            + "vulputate, purus justo laoreet augue, a feugiat sapien dolor ut "
            + "nisi. Sed semper augue ac felis ultrices a rutrum dui suscipit. "
            + "Praesent et mauris non tellus gravida mollis. In hac habitasse "
            + "platea dictumst. Vestibulum ante ipsum primis in faucibus orci "
            + "luctus et ultrices posuere cubilia Curae; Vestibulum mattis, "
            + "tortor sed scelerisque laoreet, tellus neque consectetur lacus, "
            + "eget ultrices arcu mi sit amet arcu. Nam gravida, nulla interdum "
            + "interdum gravida, elit velit malesuada arcu, nec aliquam lectus "
            + "velit ut turpis. Praesent pretium magna in nibh hendrerit et "
            + "elementum tellus viverra. Praesent eu ante diam. Proin risus "
            + "eros, dapibus at eleifend sit amet, blandit eget purus. "
            + "Pellentesque eu mollis orci. Sed venenatis diam a nisl tempor "
            + "congue.</p>"
            + "</html>");

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(label, BorderLayout.NORTH);
        panel.setPreferredSize(new Dimension(640, 480));
        return panel;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() { 
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(createPanel());
                frame.pack();
                frame.setVisible(true);
            }

        });
    }

}
Andrei Vajna II
  • 4,642
  • 5
  • 35
  • 38
8

There's a good technique here, scroll to the end of the article.

JLabel labelBeingUsed = myLabel;
View view = (View) labelBeingUsed.getClientProperty(BasicHTML.propertyKey);
view.setSize(scrollPane1.getWidth(), 0.0f);
float w = view.getPreferredSpan(View.X_AXIS);
float h = view.getPreferredSpan(View.Y_AXIS);
labelBeingUsed.setSize((int) w, (int) h);
Sam Barnum
  • 10,559
  • 3
  • 54
  • 60
1

This works for me perfectly. Not exactly text-wrapping, but it centers the text. Based on the answers here, I used align attribute and set center. More about align tag here

label.setText("<html><p align=\"center\">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></html>")

screenshot from my project (I can't post images yet. Sorry. Hope this helps.)

snich
  • 67
  • 1
  • 5
0

<html> wrapping works but not in all cases. If the parent container uses FlowLayout then it'll not work. Therefore I set it to BoxLayout. Look at this code snippet:

javax.swing.JPanel pRefundNote = new javax.swing.JPanel(); 
javax.swing.JLabel lbNote = new javax.swing.JLabel();

pRefundNote.setAlignmentX(0.0F); 
pRefundNote.setMaximumSize(new java.awt.Dimension(32767, 33)); 
pRefundNote.setLayout(new javax.swing.BoxLayout(pRefundNote, javax.swing.BoxLayout.X_AXIS)); 

lbNote.setText("<html>Select items using Shift or Ctrl and Up/Down keys or Mouse</html>"); 
lbNote.setVerticalAlignment(javax.swing.SwingConstants.TOP);
lbNote.setVerticalTextPosition(javax.swing.SwingConstants.TOP); 
pRefundNote.add(lbNote);

Don't add <br> because it'll break your text even if you enlarge your parent frame and pRefundNote container.

Jeff_Alieffson
  • 2,672
  • 29
  • 34
-7

If you only want to use JLabel than you can try this approach,

just display the number of characters you want to display on label using substring method.

public void setLabel(String label){
    String dispLabel=label.substring(0, numOfCharacter);
    labelComponent.setText(dispLabel);
}
Rajj
  • 101
  • 7