If you are using a JEditorPane to display HTML, and that HTML contains links, there is no built-in function to automatically detect if the user clicks on a link. What’s the solution to this problem? Create a HyperlinkListener. Here’s how…
Recently for a project, I had to use a JEditorPane to display some basic HTML which contained a few links. I also needed to have the program browse to the URL using the default browser upon clicking on the link. Fortunately, using a HyperlinkListener and the Desktop class, this was easy to do.
The Code
The following class detects when a user clicks on a hyperlink within a JEditorPane. Upon detection, the default browser will open and browse to the URL.
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class EditorHyperlinkListener implements HyperlinkListener {
public EditorHyperlinkListener() {}
/**
* This method opens the browser and browses
* to the URL in the JEditorPane.
*/
public void hyperlinkUpdate(HyperlinkEvent e) {
if ( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED ) {
if ( Desktop.isDesktopSupported() ) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse( new URI( e.getURL().toString() ) );
} catch ( IOException ex ) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
} // end try
} // end if
} // end if
} // end method hyperlinkUpdate
} // end class EditorHyperlinkListener
All that’s left is to add the hyperlink listener to your JEditorPane like so:
myJEditorPane.addHyperlinkListener( new EditorHyperlinkListener() );
where myJEditorPane is the name of your JEditorPane.
Tags: hyperlink, jeditorpane, link, url
