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?
There's a few parts to this:
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);
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>");
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With