Add HTML content to Document associated with JTextPane

Serhiy picture Serhiy · Feb 27, 2011 · Viewed 14.6k times · Source

I have a question regarding some simple console I'm making. I know that it's possible to add html content to JTextPane with function setText() with previously set setContentType("text/html"); . But for the needs of my application I need to work directly with javax.swing.text.Document, which I get with getDocument() function(for example for removing the lines and appending the new ones, yes it's kind of console I'm making and I have already seen several examples in previous StackOverflow questions, but none of them serves my needs). So, what I want is insert the HTML to the document and have it correctly rendered on my JTextPane. The problem is when I add HTML content with insertString() method(which belongs to the document), JTextPane is not rendering it, and in output I see all the html tags. Is there any way to get this working correctly?

That's how I insert the text:

text_panel = new JTextPane();
text_panel.setContentType("text/html");

//...

Document document = text_panel.getDocument();
document.insertString(document.getLength(), line, null);
text_panel.setCaretPosition(document.getLength());

Answer

dogbane picture dogbane · Feb 27, 2011

You need to insert using an HTMLEditorKit.

    JTextPane text_panel = new JTextPane();
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = new HTMLDocument();
    text_panel.setEditorKit(kit);
    text_panel.setDocument(doc);
    kit.insertHTML(doc, doc.getLength(), "<b>hello", 0, 0, HTML.Tag.B);
    kit.insertHTML(doc, doc.getLength(), "<font color='red'><u>world</u></font>", 0, 0, null);