How to add a HyperlinkListener to a Java component

By Alvin J. Alexander, devdaily.com

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

  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. menuEditorPane.setContentType("text/html");
  4. Next, set the actual content of the JEditorPane. In my case I've done it in a method, like this:
  5.   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());
      }
    
  6. Import two needed classes, like this:
  7. import javax.swing.event.HyperlinkListener;
    import javax.swing.event.HyperlinkEvent;
    
  8. Implement a HyperlinkListener, as shown below. Note that the text you get when you look at e.getDescription() is the URL of the hyperlink.
  9. 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);
            }
          }
        }
    }
    
  10. Add your HyperlinkListener to the JEditorPane, like this:
  11. menuEditorPane.addHyperlinkListener(new MenuPaneHyperlinkListener());

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

Note that you can also use hyperlinks on other components ... labels (JLabel's) 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.


devdaily logo