How to Make a Timer in Java

by Phaedra Krizo

This tutorial is a guide to using the timer found in the Swing class of the Java programmer language, beginning with an explanation of timer methods and concluding with a complete program that illustrates basic use of the timer object. Timers can be used to specify a future action or for timing dependent or repeated activities such as animation. The unit of time used by the timer object is milliseconds.


Create a timer object: Timer (delay in milliseconds, Action listener). For example: private Timer timer1 = new Timer(1500, this);


An optional initial delay can be set. This delay will occur once after the timer is started. For example: timer1.setInitialDelay(5000);


Start timer. For example: timer1.start();


Specify the action to be performed at the timer’s intervals in the actionPerformed() method. For example: public void actionPerformed(ActionEvent e) { //action to perform code }


Stop timer. For example: timer1.stop();


The following code is a simple working example of how to use a timer to create a continuous drawing of ovals that increase in size and descend vertically down the window.

public class TimerMain { //main function instantiates TimerExample object public static void main(String[] args){ TimerExample display = new TimerExample() GO } }

//imports for TimerExample class: import java.awt.event.ActionEvent GO import java.awt.event.ActionListener GO import java.awt. GO import javax.swing. GO public class TimerExample extends JFrame implements ActionListener { private JPanel container GO JLabel labelCounter GO private Timer timer1 = new Timer(250, this) GO int w,x,y,z = 1 GO public TimerExample() { //set initial delay to 1000 milliseconds timer1.setInitialDelay(1150) GO

    //initialize window
    container = new JPanel();   

GO this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) GO setSize(200,200) GO this.setVisible(true) GO

    //start timer

GO } /* * when timer begins this method draws ovals that increase in size * and descend vertically down the window / public void actionPerformed(ActionEvent e) { if (z < 100){ Graphics g = container.getGraphics() GO g.drawOval(w,x,y,z) GO w = w+2 GO x = x+2 GO y = y+2 GO z = z+2 GO } else //stop timer (and drawing) when z coordinate is greater than 99 timer1.stop() GO } }

Items you will need


About the Author

Phaedra Krizo has a Bachelor of Arts degree in film studies from UC Santa Barbara and is currently working toward a Master of Science degree in computer science. She has extensive experience writing training material and business process documentation for major computer companies. She lives in Northern California.