首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java简单聊天框

Java简单聊天框
EN

Stack Overflow用户
提问于 2010-03-13 04:58:20
回答 2查看 7.9K关注 0票数 1

我正在尝试创建一个非常简单的聊天窗口,它只具有显示一些文本的能力,这些文本是我不时添加的。然而,当我试图将文本附加到窗口时,我得到了以下运行时错误:

代码语言:javascript
复制
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)

下面是处理基本操作的类:

代码语言:javascript
复制
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");
    }
}
}

如果有更简单的方法,请一定要让我知道。我只需要一个单一的字体类型的文本,并由用户不可编辑。除此之外,我只需要能够在飞行中附加文本。

EN

回答 2

Stack Overflow用户

发布于 2010-03-13 05:13:16

不要扩展JScrollPane。您不会向其添加任何功能。

看起来基本的问题是您试图将文本窗格添加到滚动窗格中。这不是它的工作方式。您需要将文本窗格添加到视口中。执行此操作的最简单方法是:

代码语言:javascript
复制
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane( textPane );

代码语言:javascript
复制
scrollPane.setViewportView( textPane );
票数 2
EN

Stack Overflow用户

发布于 2010-03-13 05:10:59

代码语言:javascript
复制
public JTextPane getTextPane() {
    return (JTextPane) this.getComponent(0);
}

this.getComponent(0)将返回ScrollPane的JViewPort,而不是您的JTextPane。它不能被强制转换,所以你得到了你的异常。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2435854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档