Use Adjustment Events in Swing : AdjustmentListener « Swing Event « Java Tutorial





import java.awt.BorderLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;

public class Main extends JFrame implements AdjustmentListener {
  JScrollBar bar = new JScrollBar(SwingConstants.HORIZONTAL, 50, 10, 0, 100);

  public Main() {
    setSize(350, 100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    bar.addAdjustmentListener(this);
    JPanel pane = new JPanel();
    pane.setLayout(new BorderLayout());
    pane.add(bar, "South");
    setContentPane(pane);
  }

  public static void main(String[] arguments) {
    JFrame frame = new Main();
    frame.setVisible(true);
  }

  public void adjustmentValueChanged(AdjustmentEvent evt) {
    Object source = evt.getSource();
    int newValue = bar.getValue();
    System.out.println(newValue);
    repaint();
  }
}










15.6.AdjustmentListener
15.6.1.Use Adjustment Events in Swing