Java Reference
In-Depth Information
33
34 // called at regular intervals by timer to redraw the panel
35
public void
actionPerformed(ActionEvent event) {
36 p1.x += dx;
37 p2.y += dy;
38
if
(p1.x <= 0 || p1.x + 70 >= getWidth()) {
39 dx = -dx; // rectangle 1 has hit left/right edge
40 }
41
if
(p2.y <= 0 || p2.y + 80 >= getHeight()) {
42 dy = -dy; // rectangle 2 has hit top/bottom edge
43 }
44
45 repaint(); // instruct the panel to redraw itself
46 }
47 }
Here's the graphical window that is produced as output, which animates the rec-
tangles as we intended:
Table 14.10 lists several methods of the
Timer
class.
Table 14.10
Useful Methods of
Timer
Objects
public Timer(int msDelay, ActionListener listener)
Creates a
Timer
that activates the given
ActionListener
every
msDelay
milliseconds.
public void start()
Tells the timer to start ticking and to activate its
ActionListener
.
public void stop()
Tells the timer to stop ticking and not to activate its
ActionListener
.
Search WWH ::
Custom Search