Listening for Hyperlink Events from a JEditorPane Component - Java Swing

Java examples for Swing:JEditorPane

Description

Listening for Hyperlink Events from a JEditorPane Component

Demo Code

import java.io.IOException;

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

public class Main {
  public static void main(String[] argv) {
    try {//from  w w  w.  jav a2  s  . c o  m
      String url = "http://java2s.com";
      JEditorPane editorPane = new JEditorPane(url);
      editorPane.setEditable(false);
      editorPane.addHyperlinkListener(new MyHyperlinkListener());
    } catch (IOException e) {
    }
  }
}

class MyHyperlinkListener implements HyperlinkListener {
  public void hyperlinkUpdate(HyperlinkEvent evt) {
    if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      JEditorPane pane = (JEditorPane) evt.getSource();
      try {
        // Show the new page in the editor pane.
        pane.setPage(evt.getURL());
      } catch (IOException e) {
      }
    }
  }
}

Related Tutorials