Java Reference
In-Depth Information
d. A JComponent object is a JPanel .
e. A JToggleButton object is a JButton .
f. A JRadioButton is a Component .
SR 9.24 What benefits do you derive by having your applet class extend the
Java library's JApplet class?
9.7 Extending Adapter Classes
In previous event-based examples, we've created the listener classes by imple-
menting a particular listener interface. For instance, to create a class that listens
for mouse events, we created a listener class that implements the MouseListener
interface. As we saw in the Dots and RubberLines programs in Chapter 8, a
listener interface often contains event methods that are not
important to a particular program, in which case we pro-
vided empty definitions to satisfy the interface requirement.
An alternative technique for creating a listener class is to
extend an event adapter class. Each listener interface that con-
tains more than one method has a corresponding adapter class
that already contains empty definitions for all of the methods in
the interface. To create a listener, we can derive a new listener class from the appro-
priate adapter class and override any event methods in which we are interested. Using
this technique, we no longer need to provide empty definitions for unused methods.
KEY CONCEPT
A listener class can be created by
deriving it from an event adapter
class.
The program shown in Listing 9.13 displays a panel that responds to mouse
click events. Whenever the mouse button is clicked over the panel, a line is drawn
from the location of the mouse pointer to the center of the panel. The distance
that line represents in pixels is displayed.
The listener class is implemented as an inner class of the OffCenterPanel
class, shown in Listing 9.14. Instead of implementing the MouseListener inter-
face directly as we have done in previous examples, this listener extends the
MouseAdapter class, which is defined in the java.awt.event package of the Java
standard class library. The MouseAdapter class implements the MouseListener
interface and contains empty definitions for all of the mouse event methods. In
our listener class, we override the definition of the mouseClicked method to suit
our needs. Because we inherit the other empty methods corresponding to the rest
of the mouse events, we don't have to provide our own empty definitions.
Because of inheritance, we now have a choice when it comes to creating event
listeners. We can implement an event listener interface, or we can extend an event
adapter class. This is a design decision that should be considered carefully. The
best technique depends on the situation.
 
Search WWH ::




Custom Search