Java Reference
In-Depth Information
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 by a given amount.
28 @param x
the amount to move in the x-direction
29 @param y
the amount to move in the y-direction
30 */
31
public void
moveBy(
int
dx,
int
dy)
32 {
33 box.translate(dx, dy);
34 repaint();
35 }
36
37
private
Rectangle box;
38
39
private static final int
BOX_X =
100
;
40
private static final int
BOX_Y =
100
;
41
private static final int
BOX_WIDTH =
20
;
42
private static final int
BOX_HEIGHT =
30
;
43 }
419
420
Note the call to
repaint
in the
moveBy
method. This call is necessary to ensure
that the component is repainted after the state of the rectangle object has been
changed. Keep in mind that the component object does not contain the pixels that
show the drawing. The component merely contains a
Rectangle
object, which
itself contains four coordinate values. Calling
translate
updates the rectangle
coordinate values. The call to
repaint
forces a call to the
paintComponent
method. The
paintComponent
method redraws the component, causing the
rectangle to appear at the updated location.