Handle change event for JScrollBar in Java

Description

The following code shows how to handle change event for JScrollBar.

Example


 //from  w  w w. j  a v a2 s  . c o m
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 Main {
  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);
  }
}

The code above generates the following result.

Handle change event for JScrollBar in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer