View RSS Feed

Java Swing

How to Write a Change Listener

Rate this Entry
by , 04-26-2012 at 09:24 PM (887 Views)
Property change listener and a change listener are similar. On an object, change listener gets register, typically at component. However, it may be some other object and when object is changed notification is sent to the listener. In case of change listener, notification of any sort of change is not sent to the listener but changing of the source object is notified. Hence, change listeners are considered as more useful only when it becomes necessary to be aware that when object gets changed.

Swing components like JViewPort and JTabbedPane depends upon change events fot sake of basic functions- spinners, sliders, color choosers etc. In order to learn regarding the changes of slider value, change listener shall be registered. In similar way, change listener shall be registered at the color chooser to be aware of new color choosen by the user. On a spinner, change listener is chosen and in release 1.4 the introduced component needs to be sent notification that when value of the spinner changes.

For a slider, handling code for the change event is given below:
Java Code:
//...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();

Submit "How to Write a Change Listener" to Facebook Submit "How to Write a Change Listener" to Digg Submit "How to Write a Change Listener" to Submit "How to Write a Change Listener" to StumbleUpon Submit "How to Write a Change Listener" to Google