The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
< Day Day Up > |
A change listener is similar to a property-change listener. A change listener is registered on an object ”typically a component, but it could be another object, such as a model ”and the listener is notified when the object has changed. The big difference from a property-change listener is that a change listener is not notified of what has changed, but simply that the source object has changed. Therefore, a change listener is most useful when it is only necessary to know when an object has changed in any way. Three Swing components rely on change events for basic functionality ”sliders, color choosers , and spinners. 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. You register a change listener on a spinner, a component introduced in release 1.4, to be notified when the spinner's value changes. Here's an example of change event-handling code for a slider: [4] [4] You can find the source file, SliderDemo.java , on the CD at: JavaTutorial/uiswing/components/example-1dot4/index.html#SliderDemo . //...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(); ... } } } The Change Listener API
Because ChangeListener has only one method (see Table 5), it has no corresponding adapter class. Table 6 describes the method in the ChangeEvent class. Also see the ChangeListener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/ChangeListener.html. The ChangeEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/ChangeEvent.html. Table 5. The ChangeListener Interface
Table 6. The ChangeEvent Class
Examples That Use Change Listeners
The following examples use change listeners.
|
< Day Day Up > |