【问题标题】:Hyperlink in JEditorPaneJEdi​​torPane 中的超链接
【发布时间】:2011-04-11 05:57:57
【问题描述】:

JEditorPane ex 中显示的链接很少:

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

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

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

有什么办法吗?

【问题讨论】:

    标签: java swing hyperlink


    【解决方案1】:

    这有几个部分:

    正确设置 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 多年后仍然是一个很好的答案。现在有更好的选择吗?
    猜你喜欢
    • 2012-07-29
    • 2013-01-29
    • 2019-06-13
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多