我正在嘗試創建一個非常簡單的聊天窗口,它可以顯示一些我不時添加的文本。不過,我嘗試將文本追加到窗口時得到以下運行時錯誤: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");
}
}
}
如果沒有做到這一點更簡單的方法,通過一切手段讓我知道。我只需要文本是單一字體類型,並且用戶不可編輯。除此之外,我只需要能夠動態追加文本。
我認爲這是一個錯字,應該是'getView()''不getViewportView()'。 – JRL 2010-03-12 21:17:18
@JRL:你說得對;我只是假設Swing教程是對的。這種看法傷害了我的觀點。 – 2010-03-12 21:20:03
儘管錯字已修復,但問題在於文本窗格尚未添加到視口中,因此無法解決問題。 – camickr 2010-03-12 21:21:21