A timer is an object of Timer class which is the subclass of Object class present in java.lang package. A timer fires one or more action events after regular interval of time (in milliseconds) called delay.
The amount of delay is specified at the time of creation of timer. A timer is used in a program by creating a timer object and invoking start () method. When the timer is started, an event of ActionEvent type is fired and the code enclosed in actionPerformed () of the corresponding listener class is executed. The corresponding class must implement the ActionListener interface. The timer can also be made to fire an event only once by setting its method setRepeats () to false. The methods stop () and restart () can be called to stop or restart the timer, respectively.
The Timer can be created using the following constructor.
Timer(int delay, ActionListener listener)
where,
delay is the time, in milliseconds, between the action events
listener is the action listener
Consider Example. Here, a countdown of 10 seconds is printed. After 10 seconds, the program exits.
Example: A program to demonstrate the use of timer
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TimerExample implements ActionListener
{
int second = 1;
public static void main(String str[])
{
new TimerExample();
while(true);
}
public TimerExample()
{
Timer second= new Timer(1000,this);
second.start();
}
public void actionPerformed(ActionEvent e)
{
System.out.print(” “+second);
second++;
if (second == 11)
{
System.out.print(” “);
System.out.print(“Exit out”);
System.exit(0);
}
}
}
The output of the program is as shown in Figure