Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink in JEditorPane

I have few links displayed in JEditorPane ex:

http://www.google.com/finance?q=NYSE:C

http://www.google.com/finance?q=NASDAQ:MSFT

I want that I should be able to click them and that it gets displayed in browser

Any ideas how to do it?

like image 294
Mohit Bansal Avatar asked Sep 12 '10 02:09

Mohit Bansal


1 Answers

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());
}
like image 166
Michael Mrozek Avatar answered Nov 01 '22 23:11

Michael Mrozek