event

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button