I can't figure out how JEditorPane.scrollToReference()
designed to be used with a dynamically generated HTML page. I would like to open a dialog with JEditorPane, which scrolls to the anchor of my choice. No matter how I approach the problem, the view always scrolls at the bottom of the page.
As an ugly workaround, I am currently analyzing the entire HTML document for tag binding, storing their offsets in Map<String, Integer>
, and then calling:
editorPane.setCaretPosition(anchorMap.get("anchor-name"));
... which does not even give an attractive result, since the position of the carriage in the visible rectangular box looks unpredictable and is rarely located at the top of the window. I'm looking for a more browser-like behavior when pinned text appears at the top of the visible area.
Below is a screenshot of what happens to my inconvenient workaround (there is a binding on the βheader 6β) without touching the scrollbar:

I think I missed something, but I canβt understand what exactly.
Source of my current solution:
import javax.swing.*; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.*; import javax.swing.text.html.HTMLEditorKit.*; import javax.swing.text.html.parser.*; import java.io.*; import java.awt.*; import java.util.HashMap; public class AnchorTest { public static void main(String[] args) { final String html = generateLongPage(); final HashMap<String, Integer> anchors = anchorPositions(html); SwingUtilities.invokeLater(new Runnable() { public void run() { JEditorPane editor = new JEditorPane("text/html", html); JScrollPane scroller= new JScrollPane(editor); scroller.setPreferredSize(new Dimension(400, 250));
user786233
source share