Hyperlink in JEditorPane

There’s a few parts to this:

Setup the JEditorPane correctly

The JEditorPane needs to have the context type text/html, and it needs to be uneditable for links to be clickable:

final JEditorPane editor = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);

Add the links

You need to add actual <a> tags to the editor for them to be rendered as links:

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>");

Add the link handler

By default clicking the links won’t do anything; you need a HyperlinkListener to deal with them:

editor.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
           // Do something with e.getURL() here
        }
    }
});

How you launch the browser to handle e.getURL() is up to you. One way if you’re using Java 6 and a supported platform is to use the Desktop class:

if(Desktop.isDesktopSupported()) {
    Desktop.getDesktop().browse(e.getURL().toURI());
}

Leave a Comment