HyperLinkListener example

With this example we shall show you how to use a HyperLinkListener in Java. This is very useful when you have hyperlinks in the content you present in your application. In that case it might be important to monitor the hyperlink activity of the applications. For example, you might want to interact somehow with the user every time he clicks on a hyperlink.

To work with a HyperLinkListener you should:

  • Create a new HyperLinkListener.
  • Override the methods that correspond to the events that you want to monitor about the hyperlinks e.g hyperlinkUpdate and customize as you wish the handling of the respective events. Now every time the user clicks on any hyperlink in the frame, the corresponding method will be executed.
  • Use a JEditorPane component to load some web content.
  • Use the addHyperlinkListener method to add the HyperLinkListener you’ve created.

Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.IOException;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class HyperLinkListenerExample {

    public static void main(String args[]) {

  JFrame jFrame = new JFrame();

  Container cPane = jFrame.getContentPane();

  final JEditorPane editorPane = new JEditorPane();

  try {


  } catch (IOException e) {

System.err.println("Invalid URL: " + e);



  HyperlinkListener listener = new HyperlinkListener() {


public void hyperlinkUpdate(HyperlinkEvent event) {

    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {

  try {


  } catch (IOException ioe) {

System.err.println("Error loading url from link: " + ioe);







  JScrollPane pane = new JScrollPane(editorPane);

  cPane.add(pane, BorderLayout.CENTER);

  jFrame.setSize(800, 600);


This was an example on how to use HyperLinkListener in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button