Java Reference
In-Depth Information
// Implements five methods
}
MouseListener listener = new MyMouseListener();
component.addMouseListener(listener);
In our sample program, a user clicks on a component containing a rectangle.
Whenever the mouse button is pressed, the rectangle is moved to the mouse location.
We first enhance the RectangleComponent class and add a moveTo method to
move the rectangle to a new position.
ch09/mouse/RectangleComponent.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import java.awt.Rectangle;
4 import javax.swing.JComponent;
5
6 /**
7 This component displays a rectangle that can be moved.
8 */
9 public class RectangleComponent extends
JComponent
10 {
11 public RectangleComponent()
12 {
13 // The rectangle that the paint method draws
14 box = new Rectangle(BOX_X, BOX_Y,
15 BOX_WIDTH, BOX_HEIGHT);
16 }
17
18 public void paintComponent(Graphics g)
19 {
20 super .paintComponent(g);
21 Graphics2D g2 = (Graphics2D) g;
22
23 g2.draw(box);
24 }
25
26 /**
27 Moves the rectangle to the given location.
28 @param x the x-position of the new location
29 @param y the y-position of the new location
422
423
Search WWH ::




Custom Search