Java Reference
In-Depth Information
A timer generates timer events at fixed intervals.
When you use a timer, you specify the frequency of the events and an object of a
class that implements the
ActionListener
interface. Place whatever action you
want to occur inside the
actionPerformed
method. Finally, start the timer.
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// This action will be executed at each timer event
Place listener action here
}
}
MyListener listener = new MyListener();
Timer t = new Timer (interval, listener);
t.start();
418
419
Then the timer calls the
actionPerformed
method of the
listener
object
every
interval
milliseconds.
Our sample program will display a moving rectangle. We first supply a
RectangleComponent
class with a
moveBy
method that moves the rectangle by
a given amount.
ch09/timer/RectangleComponent.java
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
public
RectangleComponent()
12 {
13
//
The rectangle that the paint method draws