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 回答