JEditorPane中的超链接

14
1个回答

45

这个问题有几个部分:

正确设置JEditorPane

JEditorPane需要具有上下文类型text/html,且需要设置为不可编辑,以使链接可以被点击:

final JEditorPane editor = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);

添加链接

您需要在编辑器中添加实际的<a>标签,以便它们被渲染为链接:

editor.setText("<a href=\"http://www.google.com/finance?q=NYSE:C\">C</a>, <a href=\"http://www.google.com/finance?q=NASDAQ:MSFT\">MSFT</a>");

添加链接处理程序

默认情况下,单击链接不会有任何反应;你需要一个HyperlinkListener来处理它们:

editor.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
           // Do something with e.getURL() here
        }
    }
});

如何启动浏览器来处理e.getURL()取决于你的选择。如果你正在使用Java 6且支持平台,则一种方法是使用Desktop类:

if(Desktop.isDesktopSupported()) {
    Desktop.getDesktop().browse(e.getURL().toURI());
}

10多年过去了,这仍然是一个很好的答案。现在有更好的选择吗? - Rob G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接