How to Make a Timer in Java
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.
Things You'll Need
- Java Standard Development Kit (SDK)
- Java Integrated Development Environment (IDE)
Instructions
-
-
1
Create a timer object: Timer (delay in milliseconds, Action listener). For example:
private Timer timer1 = new Timer(1500, this); -
2
An optional initial delay can be set. This delay will occur once after the timer is started. For example:
timer1.setInitialDelay(5000); -
-
3
Start timer. For example:
timer1.start(); -
4
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
} -
5
Stop timer. For example:
timer1.stop(); -
6
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();
}
}//imports for TimerExample class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class TimerExample extends JFrame implements ActionListener {
private JPanel container;
JLabel labelCounter;
private Timer timer1 = new Timer(250, this);
int w,x,y,z = 1;
public TimerExample() {
//set initial delay to 1000 milliseconds
timer1.setInitialDelay(1150);//initialize window
container = new JPanel();
this.add(container);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,200);
this.setVisible(true);//start timer
timer1.start();
}
/**
* 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();
g.drawOval(w,x,y,z);
w = w+2;
x = x+2;
y = y+2;
z = z+2;
}
else //stop timer (and drawing) when z coordinate is greater than 99
timer1.stop();
}
}
-
1