Java Reference
In-Depth Information
This constructs a Point object with the specified x - and y -coordinates. Normally, the data
fields in a class should be private, but this class has two public data fields.
Java provides two listener interfaces, MouseListener and MouseMotionListener , to
handle mouse events, as shown in Figure 16.13. Implement the MouseListener interface to
listen for such actions as pressing, releasing, entering, exiting, or clicking the mouse, and
implement the MouseMotionListener interface to listen for such actions as dragging or
moving the mouse.
«interface»
java.awt.event.MouseListener
+mousePressed(e: MouseEvent): void
Invoked after the mouse button has been pressed on the source
component.
Invoked after the mouse button has been released on the
source component.
Invoked after the mouse button has been clicked (pressed and
released) on the source component.
Invoked after the mouse enters the source component.
+mouseReleased(e: MouseEvent): void
+mouseClicked(e: MouseEvent): void
+mouseEntered(e: MouseEvent): void
+mouseExited(e: MouseEvent): void
Invoked after the mouse exits the source component.
«interface»
java.awt.event.MouseMotionListener
+mouseDragged(e: MouseEvent): void
+mouseMoved(e: MouseEvent): void
Invoked after a mouse button is moved with a button pressed.
Invoked after a mouse button is moved without a button pressed.
F IGURE 16.13 The MouseListener interface handles mouse pressed, released, clicked, entered, and exited events. The
MouseMotionListener interface handles mouse dragged and moved events.
To demonstrate using mouse events, we give an example that displays a message in a panel
and enables the message to be moved using a mouse. The message moves as the mouse is
dragged, and it is always displayed at the mouse point. Listing 16.8 gives the program. A sam-
ple run of the program is shown in Figure 16.14.
F IGURE 16.14
You can move the message by dragging the mouse.
L ISTING 16.8 MoveMessageDemo.java
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class MoveMessageDemo extends JFrame {
6
VideoNote
Move message using the
mouse
public MoveMessageDemo() {
 
 
Search WWH ::




Custom Search