Java provides a special feature, called an adapter class, that call simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all me mods in an event listener interface. Masterclasses 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 arc interested. : For example, the Motionlessness. class has two methods, and mouse Moved(). The signatures of these empty method exactly as defined in the Mouse Motion Listener interface. If you were in only mouse drag events, then’
you could simply Mouse Motion Adapter and implement empty implementation would handle tile mouse motion events for you. Table 20-4 lists the different adapter classes in 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. extends Applet. Its init( ) method ere .an instance and registers that object to receive of mouse events. It also creates a~ instance mouse motion events. Both ‘of the constructors take a reference to the, applet GS in argument.
My Mouse Motion Adapter implements the mouse method. Thee other mouse motion event is silently ignored by code inherited from the Mouse Motion Adapter class. Note-that both of our 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 show Status( ) method
The basics of inner classes were explained. Here you will see why they are important. Recall that an inner class is a class defined within other class, or even within an expression. This section illustrates how inner classes can be used to simplify the code when using event adapter classes. To understand the benefit provided by inner classes, consider the applet shown in the following listing. It docs 1I0t use an inner class. Its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse is pressed. There MP t\V,~top-level classes in this program. extends.
Applet, and My Mouse Adapter extends Mouse Adapter. The unit( ) method of Mouse Pressed Demo instantiates My Mouse Adapter and provides this object as an
argument to the add Mouse Listener() method of Notice that a reference to the applet is supplied as an argument to the My Mouse Adapter constructor. nus reference is stored in an instance variable for later use by the method. When the mouse is pressed, it invokes the method of the applet through the stored applet reference. In other words, show Status( ) is invoked relative to the applet reference .