1

我有一个程序将一些 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 将替换已经存在的任何内容。

4

1 回答 1

2

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

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

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

Document doc = editorPane.getDocument();
EditorKit kit = editorPane.getEditorKit();
StringReader r = new StringReader(newUrl);
kit.read(r, doc, doc.getLength());
于 2015-08-03T18:51:31.680 回答