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 private static final int BOX_X = 100;
12 private static final int BOX_Y = 100;
13 private static final int BOX_WIDTH = 20;
14 private static final int BOX_HEIGHT = 30;
15
16 private Rectangle box;
17
18 public RectangleComponent()
19 {
20 // The rectangle that the paintComponent method draws
21 box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);
22 }
23
24 public void paintComponent(Graphics g)
25 {
26 Graphics2D g2 = (Graphics2D) g;
27 g2.draw(box);
28 }
29
30 /**
31 Moves the rectangle by a given amount.
32 @param dx the amount to move in the x-direction
33 @param dy the amount to move in the y-direction
34 */
35 public void moveRectangleBy(int dx, int dy)
36 {
37 box.translate(dx, dy);
38 repaint();
39 }
40 }