Listening to Scrolling Events with a ChangeListener : JScrollBar « Swing « Java Tutorial






Listening to Scrolling Events with a ChangeListener
import java.awt.BorderLayout;

import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class BoundedChangeListener implements ChangeListener {
  public void stateChanged(ChangeEvent changeEvent) {
    Object source = changeEvent.getSource();
    if (source instanceof BoundedRangeModel) {
      BoundedRangeModel aModel = (BoundedRangeModel) source;
      if (!aModel.getValueIsAdjusting()) {
        System.out.println("Changed: " + aModel.getValue());
      }
    } else {
      System.out.println("Something changed: " + source);
    }
  }
}

public class ScrollBarSample {
  public static void main(String args[]) {
    ChangeListener changeListener = new BoundedChangeListener();
    JScrollBar aJScrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
    BoundedRangeModel model = aJScrollBar.getModel();
    model.addChangeListener(changeListener);

    JFrame frame = new JFrame("ScrollBars R Us");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(aJScrollBar, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}








14.48.JScrollBar
14.48.1.The simplest of the bounded range components is the JScrollBarThe simplest of the bounded range components is the JScrollBar
14.48.2.Listening to Scrolling Events with a ChangeListenerListening to Scrolling Events with a ChangeListener
14.48.3.JScrollBar and Adjustment event
14.48.4.Always display scrollbar
14.48.5.Customizing a JScrollBar Look and Feel