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
28 g2.draw(box);
29 }
30
31 /**
32 Moves the rectangle to the given location.
33 @param x the x-position of the new location
34 @param y the y-position of the new location
35 */
36 public void moveTo(int x, int y)
37 {
38 box.setLocation(x, y);
39 repaint();
40 }
41 }