问题
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