TABLE 22-4
Adapter Class
Listener Interface
Commonly Used
Listener Inter faces
Implemented by
Adapter Classes
Adapter Classes
Java provides a special feature, called an adapter class, that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all
methods in an event listener interface. Adapter classes are useful when you want to receive
and process only some of the events that are handled by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the adapter classes
and implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( )
and mouseMoved( ), which are the methods defined by the MouseMotionListener
interface. If you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you.
Table 22-4 lists the commonly used adapter classes in java.awt.event and notes the
interface that each implements.
The following example demonstrates an adapter. It displays a message in the status bar
of an applet viewer or browser when the mouse is clicked or dragged. However, all other
mouse events are silently ignored. The program has three classes. AdapterDemo extends
Applet. Its init( ) method creates an instance of MyMouseAdapter and registers that object
to receive notifications of mouse events. It also creates an instance of MyMouseMotionAdapter
and registers that object to receive notifications of mouse motion events. Both of the constructors
take a reference to the applet as an argument.
MyMouseAdapter extends MouseAdapter and overrides the mouseClicked( ) method.
The other mouse events are silently ignored by code inherited from the MouseAdapter
class. MyMouseMotionAdapter extends MouseMotionAdapter and overrides the
mouseDragged( ) method. The other mouse motion event is silently ignored by code
inherited from the MouseMotionAdapter class.
Note that both of the event listener classes save a reference to the applet. This information
is provided as an argument to their constructors and is used later to invoke the showStatus( )
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks