Java Reference
In-Depth Information
Table 14.9
Useful Methods of
MouseEvent
Objects
public int getButton()
Returns the number of the mouse button that was pressed or released (1 for the left button, 2 for
the right button, and so on).
public int getClickCount()
Returns the number of times the user clicked the button. This method is useful for detecting
double-clicks.
public Point getPoint()
Returns the (
x, y
) point where the mouse event occurred.
public int getX()
Returns the
x
-coordinate where the mouse event occurred.
public int getY()
Returns the
y
-coordinate where the mouse event occurred.
For example, the mouse listener that follows could be attached to any component,
even the frame itself. It would make a message appear any time the user pressed the
mouse button:
1 // Responds to a mouse click by showing a message
2 // that indicates where the user clicked
3
4
import
java.awt.event.*;
5
import
javax.swing.*;
6
import
javax.swing.event.*;
7
8
public class
ClickListener
extends
MouseInputAdapter {
9
public void
mousePressed(MouseEvent event) {
10 JOptionPane.showMessageDialog(
null
,
11 "Mouse pressed at position ("
12 + event.getX() + ", " + event.getY() + ")");
13 }
14 }
As another example, the program that follows uses a mouse listener to set a
label's text to show the mouse's position as it moves over the label. Like the GUIs
in our previous examples, this GUI is object-oriented and serves as its own
listener:
1 // A GUI that displays the position of the mouse over a label.
2
3
import
java.awt.*;
4
import
java.awt.event.*;
Search WWH ::
Custom Search