Peter
Peter

Reputation: 11890

JLabel expanding but not word-wrapping

I have a JLabel object for displaying error messages as shown in the following code. As I understand, if the message is embedded within html tags, the label is supposed to word wrap. However, in my case, the label seems to expand horizontally. Can someone please tell me what is it that I am not doing right? Or, is there a better way to display long error messages?

Here's the code:

public class MyPanel extends JPanel {
  public MyPanel() {
    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    // Several JPanel objects inside

    // The last JPanel to show error messages

    JPanel panelErrMsg = new JPanel(new FlowLayout(FlowLayout.LEFT));

    this._lblError = new JLabel();
    this._lblError.setBorder(BorderFactory.createEmptyBorder(20, 10, 10, 10));
    this._lblError.setForeground(Color.RED);
    this._lblError.setFont(new Font("Courier New", Font.BOLD, 12));
    panelErrMsg.add(this._lblError);
    this.add(panelErrMsg);
  }

  private void DisplayMessage(String msg) {
    String newMessage = "<html><body>" + msg + "</body></html>";
    this._lblError.setText(newMessage);
  }

}

Upvotes: 1

Views: 1210

Answers (3)

Andrei Vajna II
Andrei Vajna II

Reputation: 4842

Use a BorderLayout with panelErrMsg and put the label in the NORTH position.

Upvotes: 0

David Qiao
David Qiao

Reputation: 31

You may give StyledLabel in the open source JIDE Common Layer a try. It supports line wrapping among many other features that you wish a JLabel could do.

Upvotes: 3

user695022
user695022

Reputation: 589

The label needs to have a maximum width for it to wrap. Try setting the maximum width or wrapping the text in a div tag with a width attribute.

Upvotes: 1

Related Questions