0

Java/Swing でチャット プログラムを作成しており、テキストは Jtextpane オブジェクトでレンダリングされます。現在、既存の文書に追加する方法がわからなかったため、新しいメッセージによって古いメッセージが消去されます。これを行う方法?

public void addMessage(String sender, String msg) throws BadLocationException, IOException{
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = new HTMLDocument();
    pane.setEditorKit(kit);
    pane.setDocument(doc);

    kit.insertHTML(doc, doc.getLength(), "<b>[" + sender + "]</b> " + msg, 0, 0, null);

}
4

1 に答える 1

1

HTML を使用しないでください。

代わりに、通常のテキストを使用するだけで、テキストをスタイル付き属性に関連付けることができます。

例えば:

//  create a set of attributes

Simple AttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, true);

//  Add some text

try
{
    StyledDocument doc = textPane.getStyledDocument();
    doc.insertString(doc.getLength(), "\nEnd of text", keyWord );
}
catch(Exception e) {}
于 2015-08-26T19:21:55.403 に答える