Java: Scrolling a JScrollPane (JEditorPane) to the bottom

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.

7 Comments »

  1. 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!

  2. Ryan Marcus said

    Glad I could help.

    Thanks for being comment #400!

  3. Tanks for this .. really work fine !

  4. Virux said

    Beautiful!
    And to think I have been writing hundreds of lines of code to figure this out!

    A life saver for sure.

  5. Nicklas Jepsen said

    You just saved me from endless hours of figuring out how to do this.
    Thank you!

  6. Danny said

    Ever tried reading the SDK Docs?

    • Ryan Marcus said

      I can’t tell if that is an attempt at a put-down, a sarcastic comment, or an attack on my or the above commenters ability as programmers… either way, of course I’ve read the SDK docs, that’s how I figured it out.

RSS feed for comments on this post · TrackBack URI

Leave a Comment