【问题标题】:HyperLinkListener not triggering - java swingHyperLinkListener 未触发 - java swing
【发布时间】:2015-07-30 23:30:46
【问题描述】:

我正在尝试使用超链接实现 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>

这导致了:

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

其他信息:

我正在 Ubuntu 14.04 上对此进行测试。 我已将外观设置为系统。

【问题讨论】:

    标签: java html swing


    【解决方案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,因为我在这台 PC 上没有 jdk8)

    【讨论】:

    • 此问题与JFrame/JDialog 无关,与editorPane.setEditable(false); 无关。编辑器窗格只会在不可编辑时触发事件。
    • 我很高兴地说安德鲁是正确的。一旦我使窗格不可编辑,它就可以完美运行。您能否将此作为答案,以便我选择它?
    • 哎呀,我错过了。谢谢安德鲁!
    • “你能把这个作为答案,以便我可以选择它吗?” 我希望看到@AndreaIacono 在他们的答案中添加代码注释以达到editorPane.setEditable(false); // otherwise ignores hyperlink events! 的效果.. 这是一个可靠的答案(包括正确的方法调用),只需稍作调整/澄清即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多