Java简单聊天框
问题描述:
我正在尝试创建一个非常简单的聊天窗口,它可以显示一些我不时添加的文本。不过,我尝试将文本追加到窗口时得到以下运行时错误: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");
}
}
}
如果没有做到这一点更简单的方法,通过一切手段让我知道。我只需要文本是单一字体类型,并且用户不可编辑。除此之外,我只需要能够动态追加文本。
答
你有两个选择:
- 商店
JTextPane
在一个成员变量,并返回里面getTextPane()
。 -
修改
getTextPane
返回JViewPort
的看法,这样return (JTextPane) getViewport().getView();
见Swing tutorials更多细节。
此外,正如camickr(和教程)指出的,使用add
和JScrollPane
是不正确的。您应该将组件传递给构造函数或使用setViewportView
。作为一个方面说明,我尽量不要继承Swing组件,除非它是绝对必要的(比继承更喜欢组合)。但这与问题并不特别相关。
答
public JTextPane getTextPane() {
return (JTextPane) this.getComponent(0);
}
this.getComponent(0)
将返回滚动窗格的JViewPort
,不是你的JTextPane
。它不能铸造,所以你得到你的例外。
答
请勿扩展JScrollPane。您不会添加任何功能。
它看起来像基本问题是,您正试图将文本窗格添加到滚动窗格。这不是它的工作方式。您需要将文本窗格添加到视口。最简单的方法来做到这一点是:
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
或
scrollPane.setViewportView(textPane);
我认为这是一个错字,应该是'getView()''不getViewportView()'。 – JRL 2010-03-12 21:17:18
@JRL:你说得对;我只是假设Swing教程是对的。这种看法伤害了我的观点。 – 2010-03-12 21:20:03
尽管错字已修复,但问题在于文本窗格尚未添加到视口中,因此无法解决问题。 – camickr 2010-03-12 21:21:21