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