1

我有一个用于显示错误消息的 JLabel 对象,如以下代码所示。据我了解,如果消息嵌入在 html 标签中,则标签应该是自动换行。但是,在我的情况下,标签似乎水平扩展。有人可以告诉我我做错了什么吗?或者,有没有更好的方法来显示长错误消息?

这是代码:

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

}
4

3 回答 3

3

你可以试试开源 JIDE Common Layer 中的 StyledLabel。它支持您希望 JLabel 可以执行的许多其他功能中的换行。

于 2012-01-11T22:58:53.783 回答
1

标签需要具有最大宽度才能包裹。尝试设置最大宽度或将文本包装在具有宽度属性的 div 标签中。

于 2012-01-11T21:08:18.753 回答
0

使用BorderLayoutwithpanelErrMsg并将标签放在 NORTH 位置。

于 2012-03-14T15:35:38.987 回答