Hunt this blog

Wednesday, July 8, 2009

How to add a HyperlinkListener to a Java component

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:

menuEditorPane.setContentType("text/html");

3. Next, set the actual content of the JEditorPane. In my case I've done it in a
method, like this:

void setMenuItems()
{
StringBuffer sb = new StringBuffer();
sb.append("Do the foo action
");
sb.append("Do the bar thing
");
menuEditorPane.setText(sb.toString());
}

4. Import two needed classes, like this:

import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent;

5. Implement a HyperlinkListener, as shown below. Note that the text you get when you
look at e.getDescription() is the URL of the hyperlink.

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);
}
}
}
}

6. Add your HyperlinkListener to the JEditorPane, like this:

menuEditorPane.addHyperlinkListener(new MenuPaneHyperlinkListener());