Adapters in Event Handling

All the listener interfaces we have described so far have just one associated method. Many other interfaces have several associated methods. We will use one such interface, WindowListener, as an example throughout this section. WindowListener has windowActivated, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowIconified, and windowOpened as associated methods. Recall from Section 5.4 that a class implementing an interface must have bodies for all the interface methods. This means that if we are interested in setting up only one listener interface method, windowClosing, say, we would need to write empty bodies for the other methods along the lines of

public void windowActivated((WindowEvent e))
{ }


To avoid this, we can use an adapter class: this implements empty bodies for all the interface methods. All event listener interfaces containing more than one method definition have a corresponding adapter class. In the case of WindowListener, this is WindowAdapter. The application class is defined as a subclass of the adapter class, and any nonempty interface methods are written within the application class.

If our application is a frame or applet subclass, then we cannot also define the application as a subclass of WindowAdapter. However, we can use inner classes. The following code fragment shows an inner class, MyWindowAdapter, that implements the windowClosing method. This, in turn, terminates the application when the user closes
the main window.

class MyWindowAdapter extends WindowAdapter
{
Publicvoid windowClosing(WindowEvent e)
{
System.exit(0);
}
}


The listener registration is performed by the statement

this.addWindowListener(new MyWindowAdapter() );

Note we do not register the application object to act as a listener, but an instance of the MyWindowAdapter class. The component for which we are registering a listener is the component involved when a user shuts the main window. This component is the current frame instance, identified by the keyword this.

If we create only a single object of the MyWindowAdapter class, we can dispense with giving the adapter subclass a name by using an anonymous inner class. We can replace the preceding MyWindowAdapter class and the addWindowListener statement with

this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});


This syntax reads as define an anonymous inner class as a subclass of WindowAdapter,create an instance of this inner class, and use this instance as an argument to the
addWindowListener method.

No comments:

Post a Comment