Detecting JScrollPane events

Add a AdjustmentListener to the horizontal or vertical scrollbar of the JScrollPane (you can get its reference with the methods getHorizontalScrollBar and getVerticalScrollBar).

Note that the AdjustmentType will always be AdjustmentEvent.TRACK.
(From the API: “Note that the AdjustmentEvents type property will always have a placeholder value of AdjustmentEvent.TRACK because all changes to a BoundedRangeModels value are considered equivalent. To change the value of a BoundedRangeModel one just sets its value property, i.e. model.setValue(123). No information about the origin of the change, e.g. it’s a block decrement, is provided. We don’t try fabricate the origin of the change here.”)

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout());
 
      JPanel panel = createPanel();
 
      JScrollPane scrollpane = new JScrollPane(panel);
      JScrollBar scrollbar = scrollpane.getVerticalScrollBar();
      scrollbar.addAdjustmentListener(new AdjustmentListener() {
         public void adjustmentValueChanged(AdjustmentEvent ae) {
            System.out.println(translateAdjustmentEvent(ae));
         }
      });
 
      getContentPane().add(BorderLayout.CENTER, scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public String translateAdjustmentEvent(AdjustmentEvent ae) {
      String s = "type = ";
      switch(ae.getAdjustmentType()) {
         case AdjustmentEvent.UNIT_INCREMENT:
            s += "UNIT_INCREMENT"; break;
         case AdjustmentEvent.UNIT_DECREMENT:
            s += "UNIT_DECREMENT"; break;
         case AdjustmentEvent.BLOCK_INCREMENT:
            s += "BLOCK_INCREMENT"; break;
         case AdjustmentEvent.BLOCK_DECREMENT:
            s += "BLOCK_DECREMENT"; break;
         case AdjustmentEvent.TRACK:
            s += "TRACK"; break;
         default: break;
      }
      s += ", current value = " + ae.getValue();
 
      return s;
   }
 
   public static JPanel createPanel() throws Exception {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(50, 20, 10, 10));
 
      for (int i=0; i<50; i++) {
         for (int j=0; j<20; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            panel.add(label);    
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) throws Exception  {
      Main main = new Main();
      main.setSize(600, 600);
      main.setVisible(true);
   } 
}