tags:

views:

31

answers:

1

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

+4  A: 

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\"&gt;C&lt;/a&gt;, <a href=\"http://www.google.com/finance?q=NASDAQ:MSFT\"&gt;MSFT&lt;/a&gt;");

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());
}
Michael Mrozek
Thanks a lot brother
Mohit Bansal