Start of Tutorial > Start of Trail > Start of Lesson | Search |
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.
TheChangeListener
interface 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.
stateChanged
method has a single parameter: aChangeEvent
object. To get the component that fired the event, use thegetSource
method whichChangeEvent
inherits fromEventObject
. TheChangeEvent
class defines no additional methods.
The following table lists the examples that use change listeners.
Example Where Described Notes SliderDemo
and
SliderDemo2
How 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
and
ColorChooserDemo2
Getting Started Uses a change listener on the selection model of a color chooser to learn when the user changes the current color. ConverterRangeModel
,
and its subclass,
FollowerRangeModel
The Anatomy of a Swing-Based Program Implement custom models for the sliders used in the Converter
demo. Both models explicitly fire change events when necessary.
Start of Tutorial > Start of Trail > Start of Lesson | Search |