开发者

Add HTML content to Document associated with JTextPane

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() m开发者_StackOverflow社区ethod(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());


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜