Adapters
-
The final option for handling events is the adapter model. Adapters are
used in conjunction with the listener model.
-
In the listener discussion, you saw how you can implement an interface
and then tell an object you're interested in being notified when events
occur. The adapter model uses a different tactic. Instead of implementing
the listener interface in the class that receives the events, we create
another object to listen for the events. This object serves as a middleman
between the component that generates the event and the component that receives
the event.
-
The JDK contains a predefined set of adapter classes that you can extend
from. In fact, there is one for each different type of event listener.
For example, there is a ActionAdapter for the ActionListener interface.
-
What exactly is an adapter class? An adapter class is a class that implements
its corresponding interface. For example, the ActionAdapter class is essentially
the following:
public abstract class ActionAdapter
implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
}
}
Adapters don't do anything on their own. In fact, they are declared abstract
so you can't instantiate them. This is because adapter classes only exist
as a convenience.
Suppose you wanted to listen for mouse events, but only for mouse up and
mouse-down events. It's tedious to implement the entire interface for mouse
events (MouseListener) since it contains five methods and you're only interested
in two of them. An adapter class provides an empty implementation for all
the methods. You can subclass an adapter class--in this case MouseAdapter--and
only implement the two methods that you're interested in.
In order to use adapters, you must subclass them to provide any useful
functionality. To use an adapter, you subclass it, create an object of
that subclass, and register it as a listener for events.
Additional Resources:
Beans
Event Listeners
Table of Contents
Writing Applets
|