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.
