Java Reference
In-Depth Information
29 }
30 }
31
32 ActionListener listener =
new
TimerListener();
33
34 final int DELAY =
100
;
//
Milliseconds between timer
ticks
35 Timer t =
new
Timer(DELAY, listener);
36 t.start();
37 }
38
39
private static final int
FRAME_WIDTH =
300
;
40
private static final int
FRAME_HEIGHT =
400
;
41 }
420
421
S
ELF
C
HECK
19.
Why does a timer require a listener object?
20.
What would happen if you omitted the call to
repaint
in the
moveBy
method?
C
OMMON
E
RROR
9.5: Forgetting to Repaint
You have to be careful when your event handlers change the data in a painted
component. When you make a change to the data, the component is not
automatically painted with the new data. You must tell the Swing framework that
the component needs to be repainted, by calling the
repaint
method either in the
event handler or in the component's mutator methods. Your component's
paintComponent
method will then be invoked at an opportune moment, with
an appropriate
Graphics
object. Note that you should not call the
paintComponent
method directly.
This is a concern only for your own painted components. When you make a
change to a standard Swing component such as a
JLabel
, the component is
automatically repainted.