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?
Just use the reference to your JScrollPane object, get the vertical scroll bar from it using getVerticalScrollBar , and then call setUnitIncrement on it, like this: myJScrollPane. getVerticalScrollBar(). setUnitIncrement(16);
What is the difference between a Scrollbar and a JScrollPane ? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
To show the scrollbars always on the webpage, use overflow: scroll Property. It will add both horizontal and vertical scrollbars to the webpage. To add only horizontal scrollbar use overflow-x: scroll property and for vertical scrollbar use overflow-y: scroll property.
A standard scroll bar is located in the nonclient area of a window. It is created with the window and displayed when the window is displayed. The sole purpose of a standard scroll bar is to enable the user to generate scrolling requests for viewing the entire content of the client area.
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.
The following solved the problem for me, after 50 minutes of despair:
JTextPane.grabFocus();
JTextPane.setCaretPosition(20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With