Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners

How to Write a Change Listener

Change events occur when a component that has state changes state. For example, a slider generates change events when a user moves the slider's knob.

Change Event Methods

The ChangeListener(in the API reference documentation) interface has just one method, so it has no corresponding adapter class. Here's the method:
void stateChanged(ChangeEvent)
Called when the listened-to component changes state.

Examples of Handling Change Events

Here is the change event handling code from an application named SliderDemo:
class SliderListener implements ChangeListener {
    public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider)e.getSource();
        if (!source.getValueIsAdjusting()) {
            int fps = (int)((JSlider)e.getSource()).getValue();
            if (fps == 0) {
                if (!frozen) stopAnimation();
            } else {
                delay = 1000 / fps;
                timer.setDelay(delay);
                if (frozen) startAnimation();
            }
        }    
    }
}
The SliderDemo program is described in How to Use Sliders(in the Creating a User Interface trail). You can find the entire program in SliderDemo.java.

Here are a few more source files that use change listeners:

The ChangeEvent Class

The stateChanged method has a single parameter: a ChangeEvent(in the API reference documentation) object. To get the component that generated the event, use the getSource method which ChangeEvent inherits from EventObject. The ChangeEvent class defines no additional methods.


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners