Java: Linebreaks in JLabels?

Viewed 55323

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 Answers

I did not manage to specify a maximum width for a label but you can specify a concrete width. By measuring the current width of a JLabel we can only apply the new fixed width if the JLabels's width is higher that our maxWidth:

JLabel label = new JLabel("<html>" + myVeryLongMessage + "<html>");
int maxWidth = 400;
Dimension size = label.getPreferredSize();
if (size.width > maxWidth) {
    // Estimate the number of lines
    int lineCount = (int) Math.ceil(((double) size.width) / maxWidth);
    lineCount += 1; // Add one extra line as reserve
    size.width = maxWidth; // Apply the maximum width
    // Increase the height so that all lines will be visible
    size.height *= lineCount;
    label.setPreferredSize(size);
}

You can use a JTextArea and disable the TextArea, this way, you will only display what you want, and the user won't be able to type in

JTextArea area = new JTextArea("Here \n\n you \n\n put \n\n your \n\n text");
area.setBounds(10, 11, 500, 143);
area.setEditable(false);
yourPannel.add(area);
Related