Java hyperlinks and the HyperLinkListener class

Using hypertext and hyperlinks in Java Swing applications makes them look more like web applications, and that's often a very good thing. Here's a quick example of how to add a Java HyperlinkListener to a component in Java. In this case the component I'm going to use is a JEditorPane.

menuEditorPane.setContentType("text/html");
  void setMenuItems()
  {
    StringBuffer sb = new StringBuffer();
    sb.append("<a href=\"doFoo\">Do the foo action</a><br>");
    sb.append("<a href=\"doBar\">Do the bar thing</a><br>");
    menuEditorPane.setText(sb.toString());
  }
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent;
class MenuPaneHyperlinkListener implements HyperlinkListener
{
    public void hyperlinkUpdate(HyperlinkEvent e) {
      if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
        StringTokenizer st = new StringTokenizer(e.getDescription(), " ");
        if (st.hasMoreTokens()) {
          String s = st.nextToken();
          System.err.println("token: " + s);
        }
      }
    }
}
menuEditorPane.addHyperlinkListener(new MenuPaneHyperlinkListener());
  1. First, create JEditorPane, and place it on a container. I've created an object named menuEditorPane that is a a JEditorPane.
  2. Next, set the content type of the JEditorPane to "text/html", like this:
  3. Next, set the actual content of the JEditorPane. In my case I've done it in a method, like this:
  4. Import two needed classes, like this:
  5. Implement a HyperlinkListener, as shown in the code below. Note that the text you get when you look at e.getDescription() is the URL of the hyperlink.
  6. Add your HyperlinkListener to the JEditorPane, like this:

That's all you need to do to create a hyperlink in your Java code. Of course you'll want to implement your own behavior in the hyperlinkUpdate method of the MenuPaneHyperlinkListener class, but hopefully this example hyperlink code is enough to provide the initial legwork for you.

Note that you can also use hyperlinks on other Java components ... labels (JLabel) are the first thing that comes to mind. It just so happens that I need a big area to work with, so I'm using a JEditorPane.

I hope that makes sense, and I hope it helps.