1

我正在尝试创建一个非常简单的聊天窗口,它能够显示一些我不时添加的文本。但是,在尝试将文本附加到窗口时出现以下运行时错误:

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

如果有更简单的方法可以做到这一点,请务必告诉我。我只需要文本是单一字体类型,并且用户无法编辑。除此之外,我只需要能够即时附加文本。

4

3 回答 3

2

你有两个选择:

  1. 将 存储JTextPane在成员变量中并在内部返回getTextPane()
  2. 修改getTextPane返回JViewPort的视图,像这样

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

有关更多详细信息,请参阅Swing 教程

此外,正如 camickr(和教程)指出的那样,使用addwith aJScrollPane是不正确的。您应该将组件传递给构造函数或使用setViewportView.

附带说明一下,除非绝对必要(更喜欢组合而不是继承),否则我尽量不要对 Swing 组件进行子类化。但这与这个问题并不特别相关。

于 2010-03-12T21:10:10.973 回答
2

不要扩展 JScrollPane。您没有向它添加任何功能。

看起来基本问题是您正在尝试将文本窗格添加到滚动窗格。这不是它的工作方式。您需要将文本窗格添加到视口。简单的方法是:

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

或者

scrollPane.setViewportView( textPane );
于 2010-03-12T21:13:15.700 回答
1
public JTextPane getTextPane() {
    return (JTextPane) this.getComponent(0);
}

this.getComponent(0)正在返回 ScrollPane 的JViewPort,而不是您的JTextPane. 它不能被铸造,所以你得到你的例外。

于 2010-03-12T21:10:58.640 回答