Java Reference
In-Depth Information
Here is an entire program that uses our MovementListener to respond when the
user moves the mouse over a label:
1 // A GUI that listens to mouse movements over a label.
2
3 import java.awt.*;
4 import javax.swing.*;
5
6 public class MouseGUI {
7 public static void main(String[] args) {
8 JFrame frame = new JFrame();
9 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10 frame.setLayout( new FlowLayout());
11 frame.setSize( new Dimension(200, 100));
12 frame.setTitle("A frame");
13
14 JLabel label = new JLabel();
15 label.setText("Move the mouse over me!");
16 frame.add(label);
17
18 MovementListener mListener = new MovementListener();
19 label.addMouseListener(mListener);
20 label.addMouseMotionListener(mListener);
21
22 frame.setVisible( true );
23 }
24 }
The program produces the following graphical output, shown both before and after
the user moves the mouse onto the JLabel :
When the actionPerformed method is dealing with action listeners, it accepts a
parameter of type ActionEvent that represents the action that occurs. We didn't use
this object for anything in our programs. However, the corresponding parameter in
mouse listeners, which is of type MouseEvent , is very useful. Several handy pieces
of information are stored in the MouseEvent parameter. Table 14.9 lists some of the
methods of this parameter.
 
Search WWH ::




Custom Search