event

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 {

editorPane.setPage("http://www.javacodegeeks.com/");

  } catch (IOException e) {

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

System.exit(-1);

  }

  HyperlinkListener listener = new HyperlinkListener() {

@Override

public void hyperlinkUpdate(HyperlinkEvent event) {

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

  try {

editorPane.setPage(event.getURL());

  } catch (IOException ioe) {

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

  }

    }

}

  };

  editorPane.addHyperlinkListener(listener);

  editorPane.setEditable(false);

  JScrollPane pane = new JScrollPane(editorPane);

  cPane.add(pane, BorderLayout.CENTER);

  jFrame.setSize(800, 600);

  jFrame.setVisible(true);
    }
}

 
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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button