Reputation: 2276
I have this JTextPane
(wrapped in a JScrollPane
) that is backed by a HTMLEditorKit
. The contents of the JTextPane
is simple HTML with some images (local files) embedded using img tags. The problem is that when you load the the JTextPane
, it takes a split second to load and then it comes up with the scroll bar at the bottom of the page. If I do:
JTextPane text = new JTextPane();
JScrollPane scroll = new JScrollPane(text);
// do some set up...
scroll.getVerticalScrollBar().setValue(0);
it sets the scroll bar momentarily and then another thead (presumably that is in charge of loading the images) comes and knocks the scroll bar back to the bottom. I tried adding:
((AbstractDocument)text.getDocument()).setAsynchronousLoadPriority(-1);
but that did not fix it. Is there any way to get an event from either text.getDocument()
or text
that will notify me when the pane is finished loading so that I can set the scroll bar then? The alternative is that I set up another thread to wait a second or so, and then set the scroll bar, but this is a bad hack.
Your suggestions?
Upvotes: 8
Views: 16038
Reputation: 10912
The following solved the problem for me, after 50 minutes of despair:
JTextPane.grabFocus();
JTextPane.setCaretPosition(20);
Upvotes: 2
Reputation: 1902
Have you tried using invokeLater?
final JScrollPane scroll = new JScrollPane(text);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
scroll.getVerticalScrollBar().setValue(0);
}
});
If that doesn't work, digging into the image views is pretty tough so my next step would be to track down why the scrollbar is changing:
scroll.setVerticalScrollbar(new JScrollBar() {
public void setValue(int value) {
new Exception().printStackTrace();
super.setValue(value);
}
});
You could also use a debugger in the setValue() method instead of just printing the stack trace.
Upvotes: 22
Reputation: 11592
Is your app single threaded by any chance? If it is you can request a list of running threads and get notified when they finish and then set the scrollbar value. Is that an option?
Or you can provide an ImageObserver to every image loaded and set the position of the scrollbar when all images are reported loaded?
Upvotes: 0