Java Reference
In-Depth Information
message at the mouse point. When you move the mouse without pressing a button, the
mouseMoved
method is invoked. Because the listener is interested only in the mouse-dragged
event, the
mouseDragged
method is implemented (lines 36-41).
The
mouseDragged
method is invoked when you move the mouse with a button pressed.
This method obtains the mouse location using the
getX
and
getY
methods (lines 38-39) in
the
MouseEvent
class. This becomes the new location for the message. Invoking the
repaint()
method (line 40) causes
paintComponent
to be invoked (line 50), which dis-
plays the message in a new location.
16.14
What method do you use to get the mouse-point position for a mouse event?
16.15
What is the listener interface for mouse pressed, released, clicked, entered, and
exited? What is the listener interface for mouse moved and dragged?
✓
✓
Check
Point
A
listener interface adapter
is a class that provides the default implementation for all
the methods in the listener interface.
Key
Point
Because the methods in the
MouseMotionListener
interface are abstract, you must imple-
ment all of them even if your program does not care about some of the events. Java provides
support classes, called
listener interface adapters
, that provide default implementations for all
the methods in the listener interface. The default implementation is simply an empty body. Java
provides listener interface adapters for every AWT listener interface with multiple handlers. A
listener interface adapter is named
X
Adapter for
X
Listener. For example,
MouseMotionAdapter
is a listener interface adapter for
MouseMotionListener
. Table 16.2 lists some listener inter-
face adapters used in this topic.
listener interface adapter
T
ABLE
16.2
Listener Interface Adapters
Adapter
Interface
MouseListener
MouseAdapter
MouseMotionAdapter
MouseMotionListener
KeyAdapter
KeyListener
WindowAdapter
WindowListener
Using
MouseMotionAdapter
, the code in lines 34-46 in Listing 16.8 (shown in (a)) can
be replaced by the following code, as shown in (b).
addMouseMotionListener(
new
MouseMotionListener() {
@Override
/** Handle mouse-dragged event */
public void
mouseDragged(MouseEvent e){
x = e.getX();
y = e.getY();
repaint();
addMouseMotionListener(
new
{
@Override
/** Handle mouse-dragged event */
public void
mouseDragged(MouseEvent e){
x = e.getX();
y = e.getY();
repaint();
MouseMotionAdapter()
}
}
});
@Override
/** Handle mouse-moved event */
public void
mouseMoved(MouseEvent e) {
}
});
(a) Using a listener interface
(b) Using a listener interface adapter