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

2つのオプションがあります。

  1. JTextPaneをメンバー変数に格納し、それを内に返しgetTextPane()ます。
  2. 次のように、のビューgetTextPaneを返すように変更しますJViewPort

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

詳細については、Swingチュートリアルを参照してください。

また、camickr(およびチュートリアル)が指摘しているように、とaddの使用JScrollPaneは正しくありません。コンポーネントをコンストラクターに渡すか、を使用する必要があります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)JViewPortは、あなたのではなく、ScrollPaneを返しますJTextPane。キャストできないので、例外が発生します。

于 2010-03-12T21:10:58.640 に答える