Java Swing How to - Check if a JScrollBar has reached the bottom of the JScrollPane








Question

We would like to know how to check if a JScrollBar has reached the bottom of the JScrollPane.

Answer

import java.awt.Dimension;
// w  w w.ja  v  a 2s .  c  o  m
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.JViewport;

public class Main extends JPanel {
  public Main() {
    super();
    JTree tree = new JTree();
    for (int i = 0; i < tree.getRowCount(); i++) {
      tree.expandRow(i);
    }

    final JScrollPane pane = new JScrollPane(tree) {
      Dimension prefSize = new Dimension(200, 150);

      public Dimension getPreferredSize() {
        return prefSize;
      }
    };

    pane.getVerticalScrollBar().addAdjustmentListener(e -> {
      JViewport vp = pane.getViewport();
      if (vp.getView().getHeight() <= vp.getHeight() + vp.getViewPosition().y) {
        System.out.println("End");
      }
    });

    add(pane);
  }

  public static void main(String[] args) {
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main());
    frame.pack();
    frame.setVisible(true);
  }
}