java 将 HTML 内容添加到与 JTextPane 关联的文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5133240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:37:27  来源:igfitidea点击:

Add HTML content to Document associated with JTextPane

javahtmlswingdocumentjtextpane

提问by Serhiy

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?

我有一个关于我正在制作的简单控制台的问题。我知道可以setText()使用先前设置的函数将 html 内容添加到 JTextPane setContentType("text/html");。但是为了我的应用程序的需要,我需要直接使用 javax.swing.text.Document,我使用getDocument()函数获得它(例如,用于删除行并附加新行,是的,这是我正在制作的一种控制台,我在之前的 StackOverflow 问题中已经看到了几个例子,但没有一个满足我的需求)。所以,我想要的是将 HTML 插入到文档中,并让它在我的 JTextPane 上正确呈现。问题是当我使用insertString()方法(属于文档)添加 HTML 内容时,JTextPane 没有呈现它,并且在输出中我看到了所有的 html 标签。有没有办法让它正常工作?

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

回答by dogbane

You need to insert using an HTMLEditorKit.

您需要使用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);