1 |
import java.awt.Dimension; |
2 |
import java.awt.Graphics; |
3 |
import java.awt.Graphics2D; |
4 |
import java.awt.Rectangle; |
5 |
import javax.swing.JPanel; |
6 |
|
7 |
/** |
8 |
A panel that shows a rectangle. |
9 |
*/ |
10 |
class RectanglePanel extends JPanel |
11 |
{ |
12 |
/** |
13 |
Constructs a panel with the rectangle in the top left |
14 |
corner. |
15 |
*/ |
16 |
public RectanglePanel() |
17 |
{ |
18 |
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); |
19 |
// the rectangle that the paint method draws |
20 |
box = new Rectangle(0, 0, BOX_WIDTH, BOX_HEIGHT); |
21 |
} |
22 |
|
23 |
public void paintComponent(Graphics g) |
24 |
{ |
25 |
super.paintComponent(g); |
26 |
Graphics2D g2 = (Graphics2D)g; |
27 |
g2.draw(box); |
28 |
} |
29 |
|
30 |
/** |
31 |
Resets the rectangle to the top left corner. |
32 |
*/ |
33 |
public void reset() |
34 |
{ |
35 |
box.setLocation(0, 0); |
36 |
repaint(); |
37 |
} |
38 |
|
39 |
/** |
40 |
Moves the rectangle and repaints it. The rectangle |
41 |
is moved by multiples of its full width or height. |
42 |
@param dx the number of width units |
43 |
@param dy the number of height units |
44 |
*/ |
45 |
public void moveRectangle(int dx, int dy) |
46 |
{ |
47 |
box.translate(dx * BOX_WIDTH, dy * BOX_HEIGHT); |
48 |
repaint(); |
49 |
} |
50 |
|
51 |
private Rectangle box; |
52 |
private static final int BOX_WIDTH = 20; |
53 |
private static final int BOX_HEIGHT = 30; |
54 |
private static final int PANEL_WIDTH = 300; |
55 |
private static final int PANEL_HEIGHT = 300; |
56 |
} |
57 |
|