将超链接附加到 JEditorPane

Appending hyperlinks to JEditorPane

我有一个程序将一些 URL 输出到 JEditorPane。我希望 URL 成为超链接。该程序基本上会将 URLS 输出到 JEditorPane,就像它是日志一样。

我已经有点用了,但它没有超链接 URL。

这是我的代码:

JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editorPane.setEditable(false);
editorPane.addHyperlinkListener(new HyperlinkListener() {
    //listener code here
});

//some other code here

StyledDocument document = (StyledDocument) editorPane.getDocument();

String url = "http://some url";
String newUrl = "\n<a href=\""+url+"\">"+url+"</a>\n";
document.insertString(document.getLength(), "\n" + newUrl + "\n", null);

它输出的不是 http://example.com/

<a href="http://example.com/">http://example.com/</a>

如果我不使用 StyledDocument 而只是 editorPane.setText(newUrl) 它会正确地超链接 URL,但它有一个明显的问题,即 setText 将替换已经存在的任何内容。

当您使用editorPane.setText()时,该方法将使用编辑器工具包插入字符串。这意味着它将对其进行分析、设置样式,然后使用 document.insertString() 和适当的样式来创建预期的效果。

如果您直接调用 document.insertString(),您将绕过编辑器工具包 -> 无样式。查看 setText() 的源代码,了解它是如何完成的:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/javax/swing/JEditorPane.java#JEditorPane.setText%28java.lang.String%29

因为版权问题,我不能在这里复制代码。这应该让你开始:

Document doc = editorPane.getDocument();
EditorKit kit = editorPane.getEditorKit();
StringReader r = new StringReader(newUrl);
kit.read(r, doc, doc.getLength());