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