4

I want JLabel text in multiline format otherwise text will be too long. How can we do this in Java?

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228

5 Answers5

11

If you don't mind wrapping your label text in an html tag, the JLabel will automatically word wrap it when its container's width is too narrow to hold it all. For example try adding this to a GUI and then resize the GUI to be too narrow - it will wrap:

new JLabel("<html>This is a really long line that I want to wrap around.</html>");
SingleShot
  • 18,821
  • 13
  • 71
  • 101
8

I recommend creating your own custom component that emulates the JLabel style while wrapping:

import javax.swing.JTextArea;

public class TextNote extends JTextArea {
    public TextNote(String text) {
        super(text);
        setBackground(null);
        setEditable(false);
        setBorder(null);
        setLineWrap(true);
        setWrapStyleWord(true);
        setFocusable(false);
    }
}

Then you just have to call:

new TextNote("Here is multiline content.");

Make sure that you set the amount of rows (textNote.setRows(2)) if you want to pack() to calculate the height of the parent component correctly.

Michael Clark
  • 553
  • 5
  • 10
  • 1
    A couple of additions to recreate the look and feel of a real label: `setOpaque(false);` `setFont(UIManager.getFont("Label.font"));` – HughHughTeotl Sep 06 '14 at 10:53
3

I suggest to use a JTextArea instead of a JLabel

and on your JTextArea you can use the method .setWrapStyleWord(true) to change line at the end of a word.

Nettogrof
  • 2,116
  • 2
  • 15
  • 22
3

It is possible to use (basic) CSS in the HTML.

enter image description here enter image description here

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

MultiLine Label with auto adjust height. Wrap text in Label

private void wrapLabelText(JLabel label, String text) {
    FontMetrics fm = label.getFontMetrics(label.getFont());
    PlainDocument doc = new PlainDocument();
    Segment segment = new Segment();
    try {
        doc.insertString(0, text, null);
    } catch (BadLocationException e) {

    }

    StringBuffer sb = new StringBuffer("<html>");
    int noOfLine = 0;
    for (int i = 0; i < text.length();) {
        try {
            doc.getText(i, text.length() - i, segment);
        } catch (BadLocationException e) {
            throw new Error("Can't get line text");
        }
        int breakpoint = Utilities.getBreakLocation(segment, fm, 0, this.width - pointerSignWidth - insets.left - insets.right, null, 0);
        sb.append(text.substring(i, i + breakpoint));
        sb.append("<br/>");
        i += breakpoint;

        noOfLine++;
    }
    sb.append("</html>");
    label.setText(sb.toString());

    labelHeight = noOfLine * fm.getHeight();
    setSize();
}

Thanks, Jignesh Gothadiya