我正在尝试创建一个非常简单的聊天窗口,它只具有显示一些文本的能力,这些文本是我不时添加的。然而,当我试图将文本附加到窗口时,我得到了以下运行时错误:
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");
}
}
}如果有更简单的方法,请一定要让我知道。我只需要一个单一的字体类型的文本,并由用户不可编辑。除此之外,我只需要能够在飞行中附加文本。
发布于 2010-03-13 05:13:16
不要扩展JScrollPane。您不会向其添加任何功能。
看起来基本的问题是您试图将文本窗格添加到滚动窗格中。这不是它的工作方式。您需要将文本窗格添加到视口中。执行此操作的最简单方法是:
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane( textPane );或
scrollPane.setViewportView( textPane );发布于 2010-03-13 05:10:59
public JTextPane getTextPane() {
return (JTextPane) this.getComponent(0);
}this.getComponent(0)将返回ScrollPane的JViewPort,而不是您的JTextPane。它不能被强制转换,所以你得到了你的异常。
https://stackoverflow.com/questions/2435854
复制相似问题