Java: Change Listener

Introduction

Listeners and getting the slider value

Add a change listener to the slider so that it will be called when the slider is changed. The listener will be called in two situations.
  1. It will be called repeatedly while the user is dragging the slider knob thru different values, and
  2. It will also be called again when the user lets go of the knob.
If you are interested in only the final value, call the getValueIsAdjusting() method to see if the user is still moving the knob and hasn't released the mouse button. See example below.

Change Listener

A change listener must have a stateChanged(...) method, which has a ChangeEvent parameter. You can call the ChangeEvent getSource() method to get the slider which caused this event (obviously it is the same slider that you are attaching the listener to). The example below gets the value only after the user has stopped moving the knob on the slider and released the mouse button. The JSlider method getValueAdjusting() is true if the user is still has the mouse button down, and false if the user has released it.

It calls setSomething, a user defined method, to change the drawing. Most of this code is is the same for all sliders, and that only the slider name and the statements in the inner part need to change.

slider.addChangeListener(new ChangeListener() {
  public void stateChanged(ChangeEvent e) {
     JSlider source = (JSlider)e.getSource();  // get the slider
     if (!source.getValueIsAdjusting()) {
        val = source.getValue();  // get slider value
        picture.setSomething(val);  //  picture must repaint itself
     }
  }
});

Example

JSlider happiness = new JSlider(JSlider.VERTICAL, 0, 20, 10);

happiness.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider)e.getSource();
        if (!source.getValueIsAdjusting()) {
            smile = source.getValue();  // this only sets smile
            // should do something with this value now.
        }
    }
});
happiness.setMajorTickSpacing(10);
happiness.setMinorTickSpacing(1);
happiness.setPaintTicks(true);
happiness.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
content.add(happiness);