Writing Event Listeners |
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
TheChangeListener
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 namedSliderDemo
:Theclass 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(); } } } }SliderDemo
program is described in How to Use Sliders. You can find the entire program inSliderDemo.java
.Here are a few more source files that use change listeners:
The ChangeEvent Class
ThestateChanged
method has a single parameter: aChangeEvent
object. To get the component that generated the event, use thegetSource
method whichChangeEvent
inherits fromEventObject
. TheChangeEvent
class defines no additional methods.
Writing Event Listeners |