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 theactionPerformed
method. Inside that method we are going to increase the value of our counter. - Create a new
Timer
and set up the interval time. UseTimer.start()
method to fire up theTimer
. From now on theactionPerformed
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.