Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jul 13, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using the Swing Timer Class in an Application

The Swing Timer is a useful utility offered by the java.swing package in JDK 1.2. This code snippet shows how to use the timer in an application:

1. ActionListener listener = new MyActionListener();
2. Timer timer = new Timer(500, listener);
3. timer.setInitialDelay(2000);
4. timer.start();
6. // Other program code.

Line 1 constructs the timer. The argument "listener" is an ActionListener. Line 2 sets the initialdelay to 1000 milliseconds. If this call is not made, the initial delay will be 0. Line 3 starts the timer. Once it is started, the timer fires the first event to the ActionListener after 2000 milliseconds. Thereafter, an event is fired every 500 milliseconds. The MyActionListener implements the ActionListener interface. The actionPerformed() method prints out a message with the current system time each time the timer fires.

1. ActionListener listener = new ActionListener () {
2.   public void actionPerformed (ActionEvent event) {
3.     System.out.println("Timer fired, current time = " + System.currentTimeMillis());
4.   }
5. }
Ajit Sagar
Thanks for your registration, follow us on our social networks to keep up-to-date