2012-01-11 49 views
1

我有一個JLabel對象,用於顯示如以下代碼所示的錯誤消息。據我所知,如果郵件嵌入在html標籤中,則該標籤應該自動換行。然而,就我而言,標籤似乎橫向擴展。有人可以告訴我,我不正確的做法是什麼?或者,有沒有更好的方法來顯示長的錯誤信息?JLabel擴展但不是字換行

下面的代碼:

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

} 
+0

嘗試使用'setTeitable(false)'而不是'JTextPane'? – Sheriff 2012-01-11 20:54:02

+1

不可編輯的JTextArea比JTextPane更容易。這就是我的建議。另外,這個:「據我所知,如果郵件嵌入在html標籤中,標籤應該換行」,這是不正確的。 – 2012-01-11 21:08:56

+0

在玩了一段時間之後,我注意到標籤周圍的面板會導致標籤不能包裝。如果我移除面板,它會包裹。然而,文本從窗口的中間開始,並沒有離開。 setAlignmentX與LEFT_ALIGNMENT沒有區別。 – Peter 2012-01-11 21:31:38

回答

1

標籤需要有它來包裝的最大寬度。 嘗試設置最大寬度或將文本封裝在具有寬度屬性的div標記中。

+0

*「或將文本封裝在具有寬度屬性的div標記中。」*我通常會爲body元素設置一個寬度。 – 2012-01-12 03:13:35

3

您可以嘗試使用開源JIDE公共層中的StyledLabel。它支持您希望JLabel可以執行的許多其他功能之間的換行。

+0

歡迎來到StackOverflow :) – 2012-01-12 11:43:27

0

使用BorderLayoutpanelErrMsg並將標籤放在NORTH位置。