How to auto scroll to bottom in Java Swing

pathikrit picture pathikrit · Jun 16, 2011 · Viewed 17.2k times · Source

I have a simple JPanel with a JScrollPane (with vertical scrollbar as needed) on it.

Things get added to (or removed from) the JPanel and when it goes beyond the bottom of the panel, I want the JScrollPane to scroll down to the bottom automatically as needed or scroll up if some components go away from the panel.

How shall I do this? I am guessing I need some kind of listener which gets called whenever the JPanel height changes? Or is there something as simple as JScrollPanel.setAutoScroll(true)?

Answer

zerodefect picture zerodefect · Apr 3, 2013
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
        public void adjustmentValueChanged(AdjustmentEvent e) {  
            e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
        }
    });

This would be the best. Found from JScrollPane and JList auto scroll