Handling Hyperlink events on a JEditorPane

Add a HyperlinkListener to your JEditorPane, as shown in the following example. Note that a distinction is made between a normal hyperlink and a hyperlink activated in a frame. In the latter case, a HTMLFrameHyperlinkEvent will be posted.

import javax.swing.text.html.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
public class Main extends JFrame
   // need to be final to allow the inner class to access it!
   final JTextField urlTextField = new JTextField();
   final JEditorPane htmlPane = new JEditorPane();
   JButton urlButton = new JButton("Go!");
   public static void main(String []args) {
      Main main = new Main();
   public Main() { 
      urlButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {

      htmlPane.addHyperlinkListener(new HyperlinkListener() {
         public void hyperlinkUpdate (HyperlinkEvent event) {
            if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {

               if (event instanceof HTMLFrameHyperlinkEvent) {
                  HTMLDocument doc = (HTMLDocument) htmlPane.getDocument();
                  doc.processHTMLFrameHyperlinkEvent ((HTMLFrameHyperlinkEvent) event);
               else {
      getContentPane().setLayout(new BorderLayout());
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(BorderLayout.CENTER, urlTextField);
      topPanel.add(BorderLayout.EAST, urlButton);
      getContentPane().add(BorderLayout.NORTH, topPanel);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
      setSize(400, 400);

   public void loadPage(String url) {
      try {
         htmlPane.setPage(new URL(urlTextField.getText()));
      catch(Exception e) {