Home » Desktop Java » awt » event » A simple Timer example

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

A simple Timer example

With this tutorial we are going to see how to use the Timer component in Java. The Timer component is very useful when you want to schedule some tasks in your application. In our case we are going to use this component to fire up an ActionListener that prints the value of a counter.

In short, to use the Timer component you have to:

  • Create an ActionListener and override the actionPerformed method. Inside that method we are going to increase the value of our counter.
  • Create a new Timer and set up the interval time. Use Timer.start() method to fire up the Timer. From now on the actionPerformed method will fire up with the time intervals you set up in the Timer constructor.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Counter {

    private static int cnt;

    public static void main(String args[]) {

  new JFrame().setVisible(true);

  ActionListener actListner = new ActionListener() {

@Override

public void actionPerformed(ActionEvent event) {

    cnt += 1;

    System.out.println("Counter = "+cnt);

}

  };

  Timer timer = new Timer(500, actListner);

  timer.start();
    }
}

Output:

Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
Counter = 6
Counter = 7
Counter = 8
Counter = 9
Counter = 10
Counter = 11
Counter = 12
Counter = 13
Counter = 14

 
This was an example on how to work with Timer in Java.

(-2 rating, 2 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of