2010-03-12 110 views
1

我正在嘗試創建一個非常簡單的聊天窗口,它可以顯示一些我不時添加的文本。不過,我嘗試將文本追加到窗口時得到以下運行時錯誤:Java簡單聊天框

java.lang.ClassCastException: javax.swing.JViewport cannot be cast to javax.swing.JTextPane 
    at ChatBox.getTextPane(ChatBox.java:41) 
    at ChatBox.getDocument(ChatBox.java:45) 
    at ChatBox.addMessage(ChatBox.java:50) 
    at ImageTest2.main(ImageTest2.java:160) 

這裏是處理的基本操作類:

public class ChatBox extends JScrollPane { 

private Style style; 

public ChatBox() { 

    StyleContext context = new StyleContext(); 
    StyledDocument document = new DefaultStyledDocument(context); 

    style = context.getStyle(StyleContext.DEFAULT_STYLE); 
    StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT); 
    StyleConstants.setFontSize(style, 14); 
    StyleConstants.setSpaceAbove(style, 4); 
    StyleConstants.setSpaceBelow(style, 4); 

    JTextPane textPane = new JTextPane(document); 
    textPane.setEditable(false); 

    this.add(textPane); 
} 

public JTextPane getTextPane() { 
    return (JTextPane) this.getComponent(0); 
} 

public StyledDocument getDocument() { 
    return (StyledDocument) getTextPane().getStyledDocument(); 
} 

public void addMessage(String speaker, String message) { 
    String combinedMessage = speaker + ": " + message; 
    StyledDocument document = getDocument(); 

    try { 
     document.insertString(document.getLength(), combinedMessage, style); 
    } catch (BadLocationException badLocationException) { 
     System.err.println("Oops"); 
    } 
} 
} 

如果沒有做到這一點更簡單的方法,通過一切手段讓我知道。我只需要文本是單一字體類型,並且用戶不可編輯。除此之外,我只需要能夠動態追加文本。

回答

2

你有兩個選擇:

  1. 商店JTextPane在一個成員變量,並返回裏面getTextPane()
  2. 修改getTextPane返回JViewPort的看法,這樣

    return (JTextPane) getViewport().getView(); 
    

Swing tutorials更多細節。

此外,正如camickr(和教程)指出的,使用addJScrollPane是不正確的。您應該將組件傳遞給構造函數或使用setViewportView。作爲一個方面說明,我儘量不要繼承Swing組件,除非它是絕對必要的(比繼承更喜歡組合)。但這與問題並不特別相關。

+0

我認爲這是一個錯字,應該是'getView()''不getViewportView()'。 – JRL 2010-03-12 21:17:18

+0

@JRL:你說得對;我只是假設Swing教程是對的。這種看法傷害了我的觀點。 – 2010-03-12 21:20:03

+0

儘管錯字已修復,但問題在於文本窗格尚未添加到視口中,因此無法解決問題。 – camickr 2010-03-12 21:21:21

1
public JTextPane getTextPane() { 
    return (JTextPane) this.getComponent(0); 
} 

this.getComponent(0)將返回滾動窗格的JViewPort,不是你的JTextPane。它不能鑄造,所以你得到你的例外。

+0

這可能會解決所述的問題,但是,由於您無法將文本窗格添加到該窗格,因此該滾動窗格無法使用。您必須將文本窗格添加到視口以使其工作。然後我不確定是否保證文本窗格將是組件0,因爲您可以將滾動條或行頭添加到滾動窗格中。 – camickr 2010-03-12 21:23:58

+0

@camickr:我認爲你對'setViewportView()'部分是正確的,但請注意,我不提議修復,只是解釋異常。 – JRL 2010-03-12 21:33:04

+0

是的,我現在看到。 – camickr 2010-03-12 22:04:43

2

請勿擴展JScrollPane。您不會添加任何功能。

它看起來像基本問題是,您正試圖將文本窗格添加到滾動窗格。這不是它的工作方式。您需要將文本窗格添加到視口。最簡單的方法來做到這一點是:

JTextPane textPane = new JTextPane(); 
JScrollPane scrollPane = new JScrollPane(textPane); 

scrollPane.setViewportView(textPane);