Matt Matt - 1 year ago 138
Java Question

Scroll JScrollPane to bottom

I need to scroll a JScrollPane to the bottom. The JScrollPane contains a JPanel, which contains a number of JLabel's.

To scroll to the top, I just do:

scrollPane.getViewport().setViewPosition(new Point(0,0));

but how do I scroll exactly to the very bottom? (Too far and it jitters)

Answer Source

Instead of setViewPosition(), I usually use scrollRectToVisible(), described in How to Use Scroll Panes. You could use the result of an appropriate label's getBounds() for the required Rectangle.

Addendum: @Matt notes in another answer, "If you use the following code after you output text to the text area in the scrollpane, it will automatically focus on the bottom of the text area."

In the particular case of a JTextComponent, also consider using the setUpdatePolicy() method of DefaultCaret to ALWAYS_UPDATE, illustrated here.