Java Swing How to - Make JEditorPane scroll to specified HTML link








Question

We would like to know how to make JEditorPane scroll to specified HTML link.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.StringReader;
//from w w  w .  ja v  a 2 s  .c  o m
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main extends JPanel {
  private JEditorPane html;

  public Main() {
    setLayout(new BorderLayout());
    String text = "<html>one<br>two<br><a name =\"three\"></a>three<br>four<br>five<br>six<br>seven<br>eight<br>nine<br>ten</html>";
    StringReader reader = new StringReader(text);

    html = new JEditorPane();
    html.setContentType("text/html");

    try {
      html.read(reader, null);
    } catch (Exception e) {
      System.out.println(e);
    }

    JScrollPane scrollPane = new JScrollPane(html);
    scrollPane.setPreferredSize(new Dimension(400, 100));
    add(scrollPane);
    html.scrollToReference("three");

  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("EditorPaneScroll");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main());
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
  }
}