Java Swing How to - Jump to internal anchors in JEditorPane








Question

We would like to know how to jump to internal anchors in JEditorPane.

Answer

import java.awt.Point;
//  ww  w  .  j  av  a 2  s  . c  o  m
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.event.HyperlinkEvent;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new PaneWithScrollFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

class PaneWithScrollFrame extends JFrame {
  String TEXT = "<html>" + "<head>" + "</head>" + "<body>"
      + "<br/><br/><br/><br/><br/>"
      + "<br/><br/><br/><br/>"
      + "<br/><br/><br/><br/>"
      + "<br/><br/><br/><br/>"
      + "<br/><br/><br/><br/>"
      + "<p><a href=\"#top\">Go top</a></p>" + "</body>" + "</html>";
  String TOP = "#top";

  public PaneWithScrollFrame() {
    this.addComponents();
    super.setSize(640, 180);
  }

  private void addComponents() {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setContentType("text/html");
    editorPane.setEditable(false);
    editorPane.setText(TEXT);

    JScrollPane scrollpane = new JScrollPane(editorPane);

    editorPane.addHyperlinkListener(e -> {
      if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) {
        String description = e.getDescription();
        if (TOP.equals(description)) {
          JViewport viewport = scrollpane.getViewport();
          viewport.setViewPosition(new Point(0, 0));
        }
      }
    });
    super.add(scrollpane);
  }
}