JEditorPane Hyperlink swing html

时光总嘲笑我的痴心妄想 提交于 2019-12-19 11:24:58

问题


I'm having a difficult time getting the hyperlink to work in a JEditorPane. Could someone please tell me what I'm doing wrong here? I want to be able to click on the link and the browser to open to that page. Thanks in advance. :D

    bottomText.setText("<a href=\"http://www.yahoo.com\">Yahoo</a>");
    bottomText.setEditable(false);
    bottomText.setOpaque(false);
    bottomText.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
    bottomText.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {

            }
            if(Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(e.getURL().toURI());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (URISyntaxException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

        }

    });

回答1:


Wow, that was simpler then I though :P

// Move this
//bottomText.setText("<a href=\"http://www.yahoo.com\">Yahoo</a>");
bottomText.setEditable(false);
bottomText.setOpaque(false);
bottomText.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"))
// To Here
bottomText.setText("<a href=\"http://www.yahoo.com\">Yahoo</a>");

Oh, and wait till the user has clicked the link before opening the browser, had about 4 windows going before I killed you example ;)

UPDATE with Click

You were almost there ;)

bottomText.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(e.getURL().toURI());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (URISyntaxException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
});



回答2:


call bottomText.setEditorKit before bottomText.setText



来源:https://stackoverflow.com/questions/11753042/jeditorpane-hyperlink-swing-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!