JEdi​​torPane中的超链接

Moh*_*sal 12 java swing hyperlink

我在JEditorPane ex中显示的链接很少:

http://www.google.com/finance?q=NYSE:C

http://www.google.com/finance?q=NASDAQ:MSFT

我希望我能够点击它们并在浏览器中显示它

有什么想法怎么做?

Mic*_*zek 39

这有几个部分:

正确设置JEditorPane

JEditorPane需求有上下文类型text/html,并且它需要不可编辑的链接,可以点击:

final JEditorPane editor = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);
Run Code Online (Sandbox Code Playgroud)

添加链接

您需要向<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>");
Run Code Online (Sandbox Code Playgroud)

添加链接处理程序

默认情况下,单击链接将不会执行任何操作; 你需要一个HyperlinkListener处理它们:

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

如何启动浏览器来处理e.getURL()由您决定.如果您使用Java 6和支持的平台,一种方法是使用Desktop该类:

if(Desktop.isDesktopSupported()) {
    Desktop.getDesktop().browse(e.getURL().toURI());
}
Run Code Online (Sandbox Code Playgroud)