我有一个 JEditorPane
,它显示以编程方式(在运行时)生成的 HTML。
到目前为止,当我添加“行”时,我是在字符串缓冲区中重新创建整个 HTML 文本,然后将其传递给 JEditorPane.setText
方法。
现在创建的 HTML 已经变得相当大(可以达到几 MB),我会简单地在末尾添加我的新行而不是重新生成所有 HTML 文本。
我尝试在末尾追加的原因是为了避免 Swing(或工具包?)不得不再次呈现/解析整个文本。因为即使 HTML 生成不是在 EDT 中执行,而是在另一个 swingworker 线程中执行,“渲染”需要很长时间。或者最好是有一个进度条显示渲染的进度,这是不可能的(是吗?)。
所以我的想法是简单的在最后追加,如果你有更好的想法,欢迎!
由于我的文本采用 HTML 表格格式,我想在该表格的末尾附加我的新文本。为此,我尝试使用 HTMLDocument
的 insertBeforeEnd
,但即使我尝试了很多解决方案,我也无法让它工作。请注意,我只有“表格”标签。
这是我的部分代码
JEditorPane jep = new JEditorPane();
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
jep.setEditorKit(kit);
jep.setDocument(doc);
//setting dummy text within a HTML table
jep.setText("<table><tr><td>A line of text</td></tr><tr><td>Another line of text</td></tr></table>");
现在在这个表的末尾添加一些文本
//getting the Table Element
Element e = doc.getElement(doc.getDefaultRootElement(), StyleConstants.NameAttribute, HTML.Tag.TABLE);
请注意,该元素似乎已正确找到,因为 System.out.println(e.getName())
给出了“table”
现在
//inserting text at the end of the table
try {
doc.insertBeforeEnd(e, "<tr><td>A New Line</td></tr>");
} catch (BadLocationException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
给我一个异常(exception):
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: No HTMLEditorKit.Parser
at javax.swing.text.html.HTMLDocument.verifyParser(HTMLDocument.java:1500)
at javax.swing.text.html.HTMLDocument.insertBeforeEnd(HTMLDocument.java:1248)
...
编辑
我已经开始了一个关于这个后续问题的新问题,这里是链接:
https://stackoverflow.com/questions/9659209/jeditorpane-htmldocument-different-rendering-how-why
尽管在@JoopEggen 的回答下一切正常,但字体呈现不一样,我不明白为什么。在我看来,这是一个与此处发布的问题不同的问题,我在另一个问题(上面给出的链接)中提出了这个问题。但在我的案例中,它有点像这个案例的后续。
因为有些人可能会遇到同样的问题,所以我将此编辑设置为将您指向相应的线程。
最佳答案
private HTMLDocument doc;
...
JTextPane jep = jTextPane1;
jep.setContentType("text/html");
jep.setText("<html><table><tr><td>A line of text</td></tr><tr><td>Another line of text</td></tr></table>");
doc = (HTMLDocument)jep.getStyledDocument();
后跟 setText 的内容类型安装 EditorKit 并确定文档。因此,之后使用 StyledDocument。 setText("...") 再次确保采用 HTML。 (您可以使用带有“Hello!!!”的 JLabel 或 JButton。
JTextPane 比 JEditorPane 更高级(奇怪的命名)。它提供了 StyledDocument,您可以通过它做更多的事情。
其他的就好了。
关于Java HTMLDocument(insertAfterEnd、insertAfterStart、insertBeforeEnd、insertBeforeStart)不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8214316/