by Dinesh Thakur Category: Swing

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)


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();



    public TimerExample()


       Timer second= new Timer(1000,this);



    public void actionPerformed(ActionEvent e)


       System.out.print(" "+second);


       if (second == 11)


                System.out.print(" ");

                System.out.print("Exit out");





 The output of the program is as shown in Figure

         java swing timer class example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles