JEditorPane Hyperlink swing html

2020-03-30 07:42发布

问题:

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