我对我正在制作的一些简单的控制台有疑问。我知道可以将html内容添加到JTextPane,其中函数setText()
具有先前设置的setContentType("text/html");
。但是对于我的应用程序的需要,我需要直接使用javax.swing.text.Document,这是我用getDocument()
函数得到的(例如用于删除行并附加新行,是的它是一种控制台我我正在制作并且我已经在之前的StackOverflow问题中看到了几个例子,但它们都没有满足我的需求。所以,我想要的是将HTML插入到文档中并在我的JTextPane上正确呈现它。问题是当我用insertString()
方法(属于文档)添加HTML内容时,JTextPane没有渲染它,在输出中我看到所有的html标记。有没有办法让这个工作正常?
这就是我插入文字的方式:
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());
答案 0 :(得分:26)
您需要使用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);