Java Reference
In-Depth Information
Java also provides interface
MouseWheelListener
to enable applications to respond to
the
rotation of a mouse wheel
. This interface declares method
mouseWheelMoved
, which
receives a
MouseWheelEvent
as its argument. Class
MouseWheelEvent
(a subclass of
Mouse-
Event
) contains methods that enable the event handler to obtain information about the
amount of wheel rotation.
Tracking Mouse Events on a
JPanel
The
MouseTracker
application (Figs. 12.28-12.29) demonstrates the
MouseListener
and
MouseMotionListener
interface methods. The event-handler class (lines 36-97 of
Fig. 12.28) implements both interfaces. You
must
declare all seven methods from these two
interfaces when your class implements them both. Each mouse event in this example displays
a
String
in the
JLabel
called
statusBar
that is attached to the bottom of the window.
1
// Fig. 12.28: MouseTrackerFrame.java
2
// Mouse event handling.
3
import
java.awt.Color;
4
import
java.awt.BorderLayout;
5
import
java.awt.event.MouseListener;
6
import
java.awt.event.MouseMotionListener;
7
import
java.awt.event.MouseEvent;
8
import
javax.swing.JFrame;
9
import
javax.swing.JLabel;
10
import
javax.swing.JPanel;
11
12
public class
MouseTrackerFrame
extends
JFrame
13
{
14
private final
JPanel mousePanel;
// panel in which mouse events occur
15
private final
JLabel statusBar;
// displays event information
16
17
// MouseTrackerFrame constructor sets up GUI and
18
// registers mouse event handlers
19
public
MouseTrackerFrame()
20
{
21
super
(
"Demonstrating Mouse Events"
);
22
23
mousePanel =
new
JPanel();
mousePanel.setBackground(
Color.WHITE
);
add(mousePanel,
BorderLayout.CENTER
);
// add panel to JFrame
24
25
26
27
statusBar =
new
JLabel(
"Mouse outside JPanel")
;
add(statusBar,
BorderLayout.SOUTH
);
// add label to JFrame
28
29
30
// create and register listener for mouse and mouse motion events
MouseHandler handler =
new
MouseHandler();
mousePanel.addMouseListener(handler);
mousePanel.addMouseMotionListener(handler);
31
32
33
34
}
35
Fig. 12.28
|
Mouse event handling. (Part 1 of 3.)