Home » Desktop Java » awt » event » HyperLinkListener example

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply


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

Notify of