Cinaed666
Cinaed666

Reputation: 79

How to add to existing HTML in Jtextpane

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

}

Upvotes: 0

Views: 130

Answers (1)

camickr
camickr

Reputation: 324108

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

Upvotes: 1

Related Questions