|
|
Writing Event Listeners |
Change events occur whenever a component changes state. For example, a button fires a change event every time the button is pressed. The look-and-feel implementation of the button listens for change events so that it can react appropriately to the state change (repainting itself, for example). Although nothing's stopping you from registering for change events on a button, most programs don't need to do so.Two Swing components rely on change events for basic functionality -- sliders and color choosers. To learn when the value in a slider
changes, you need to register a change listener. Similarly, you need to register a change listener on a color chooser
to be informed when the user chooses a new color.
Here is an example of change event handling code for a slider:
This snippet is from a program named//...where initialization occurs: framesPerSecond.addChangeListener(new SliderListener()); ... class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)source.getValue(); ... } } }SliderDemo. You can find the source and image files for the program, along with instructions for compiling and running it, in How to Use Sliders.
The Change Event API
TheChangeListenerinterface has just one method, so it has no corresponding adapter class. Here's the method:
The
void stateChanged(ChangeEvent)- Called when the listened-to component changes state.
stateChangedmethod has a single parameter: aChangeEventobject. To get the component that fired the event, use the
getSourcemethod whichChangeEventinherits fromEventObject. TheChangeEventclass defines no additional methods.Examples that Use Change Listeners
The following table lists the examples that use change listeners.
Example Where Described Notes SliderDemo.javaand
SliderDemo2.javaHow to Use Sliders Registers a change listener on a slider that controls animation speed. The change listener ignores the change events until the user releases the slider. ColorChooserDemo.javaand
ColorChooserDemo2.javaHow to Use Color Choosers Uses a change listener on the selection model of a color chooser to learn when the user changes the current color. ConverterRangeModel.java,
and its subclass,
FollowerRangeModel.javaThe Anatomy of a Swing-Based Program Implement custom models for the sliders used in the Converterdemo. Both models explicitly fire change events when necessary.
|
|
Writing Event Listeners |