Java Swing - 如何跳轉到JEditorPane中的內部定位點
我們想知道如何跳轉到JEditorPane中的內部定位點。
import java.awt.Point;
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);
}
}