Java Reference
In-Depth Information
public void mouseDragged(MouseEvent event) {
// ...
}
public void mouseMoved(MouseEvent event) {
// ...
}
Unlike the other event-listener interfaces you have dealt with up to this point,
MouseMotionListener
does not have its own event type. Instead,
MouseEvent
objects are
used.
Because of this, you can call the same methods you would for mouse events:
getClick()
,
getPoint()
,
getX()
, and
getY()
.
The next project demonstrates how to detect and respond to mouse events. Listing 12.4
contains the
MousePrank
and
PrankPanel
classes, which implement a popular user-
interface prank—a button that tries to avoid being clicked.
LISTING 12.4
The Full Text of
MousePrank.java
1: import java.awt.*;
2: import java.awt.event.*;
3: import javax.swing.*;
4:
5: public class MousePrank extends JFrame implements ActionListener {
6: public MousePrank() {
7: super(“Message”);
8: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9: setSize(420, 220);
10: BorderLayout border = new BorderLayout();
11: setLayout(border);
12: JLabel message = new JLabel(“Click OK to close this program.”);
13: add(BorderLayout.NORTH, message);
14: PrankPanel prank = new PrankPanel();
15: prank.ok.addActionListener(this);
16: add(BorderLayout.CENTER, prank);
17: setVisible(true);
18: }
19:
20: public void actionPerformed(ActionEvent event) {
21: System.exit(0);
22: }
23:
24: public Insets getInsets() {
25: return new Insets(40, 10, 10, 10);
26: }
27: