12

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());
Cœur
  • 32,421
  • 21
  • 173
  • 232
Serhiy
  • 3,846
  • 2
  • 33
  • 62

1 Answers1

26

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);
dogbane
  • 242,394
  • 72
  • 372
  • 395
  • 1
    Thanks, this what I needed ;) – Serhiy Feb 27 '11 at 13:22
  • 1
    I was looking for this and it helped, thank you very much, but, for hyperlinks the UI rendering to show the text in blue on hovering and underlining didn't happen. Any help – Kiran Apr 12 '14 at 18:01