How to add to existing HTML in Jtextpane

自闭症网瘾萝莉.ら 提交于 2019-12-13 03:54:55

问题


I am making a chat program in Java/Swing, and the text is rendered in a Jtextpane object. Right now, a new message erases the old one, as I couldn't figure out how to add to the existing document. How to do this?

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

}

回答1:


Don't use HTML.

Instead just use regular text and then you can associate the text with styled attributes.

For example:

//  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) {}


来源:https://stackoverflow.com/questions/32234501/how-to-add-to-existing-html-in-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!