Recently, I’ve stumbled upon a difficult issue in Java. If you’ve got a JEditorPane contained in a JScrollPane, and you add text to the JEditorPane and then, on the next line, try to scroll the JEditorPane to the bottom, you’ll still end up with the scroll bar at the top. The reason is quite simple: Threading. When you call JEditorPane.setText(), you cause Java to do some stuff behind the scenes in a different thread — not the main thread. When you then try to set the scroll position on the next line, the scroll bar position will change — however, Java’s behind the scenes thread will move it back to the top — pretty standard concurrency bug. Anyway, there is a simple fix:
private void scrollPaneToBottom() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jScrollPane1.getVerticalScrollBar().setValue(
jScrollPane1.getVerticalScrollBar().getMaximum());
}
});
}
SwingUtilities.invokeLater runs a Runnable (which is pretty much a thread, for this extent and purpose.) after all of Java's behind-the-scenes stuff finishes.
Kiat said
I just had the exact same problem that had been bothered me since yesterday! Mystery solved and the solution work like a charm! Thanks!
Ryan Marcus said
Glad I could help.
Thanks for being comment #400!
Sérgio Berlotto said
Tanks for this .. really work fine !
Virux said
Beautiful!
And to think I have been writing hundreds of lines of code to figure this out!
A life saver for sure.