HyperLinkListener没有触发 - java swing

时间:2015-07-27 21:44:52

标签: java html swing

我正在尝试使用超链接实现JEditorPane。我正在使用HyperLinkListener,但它似乎永远不会触发。

代码:

JEditorPane editorPane = new JEditorPane("text/html", programInfo);

editorPane.addHyperlinkListener(e -> {
    System.out.println("CLICK");
    if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED))
        try {
            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(e.getURL().toURI());
                }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });

JOptionPane.showMessageDialog(contentPane, editorPane);

示例HTML:

 <body>
 <p><b>Author:</b> James - <a href="http://www.sample.co.uk">sample</a></p>
 </body>

这导致了这个:

Imgur upload of JEditorPane

但是当我点击链接时没有任何反应。

其他信息:

我在Ubuntu 14.04上测试了这个。 我已将Look and Feel设置为系统。

1 个答案:

答案 0 :(得分:1)

编辑:感谢@AndrewThompson找到真正的问题。 它不触发事件的原因是因为编辑器窗格仅在不可编辑时触发事件。因此,为了使代码工作,您应该在构建editorPane之后添加此行:

editorPane.setEditable(false);

您可以在下面找到一个自包含的示例:

public class TestFrame extends JFrame {

    public static void main(String[] args) {

        JEditorPane editorPane = new JEditorPane("text/html", "test <a href=\"http://example.com\">link to example.com</a>");
        editorPane.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                System.out.println("CLICK");
                if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED)) try {
                    if (Desktop.isDesktopSupported()) {
                        Desktop.getDesktop().browse(e.getURL().toURI());
                    }
                }
                catch (IOException e1) {
                    e1.printStackTrace();
                }
                catch (URISyntaxException e1) {
                    e1.printStackTrace();
                }
            }
        });
        editorPane.setEditable(false); // otherwise ignores hyperlink events!

        JFrame frame = new JFrame("EditorPane Example");
        frame.add(editorPane);
        frame.setSize(300,200);
        frame.setVisible(true);
    } }

(抱歉,我删除了lambda因为我没有在这台电脑上安装jdk8)