Tuesday, July 21, 2009

Using Timer class in java swing

The first thing that you should know is that Timer class is available both in java.util and javax.swing packages and they both are different from each other.

I will be discussing code example about the Timer class in javax.Swing package which you can use to make a countdown timer, JprogressBar or do other operations.

Below is the code example and then the explanation follows:-

import java.awt.event.*;
import javax.swing.Timer;
* @author morph
public class timer_Example extends javax.swing.JFrame implements ActionListener {
Timer timer=null;
javax.swing.JLabel label=null;
static int counter=0;
/** Creates new form timer_Example */

public timer_Example(){
//your code goes here
label=new javax.swing.JLabel("The time is 0 seconds");
timer=new Timer(1000,this);/*create a timer that generates an event after 1 second and pass it the frame object which handles the action event by implementing the ActionListener interface*/

public void actionPerformed(ActionEvent e){
javax.swing.SwingUtilities.invokeLater(new updateCount());

public class updateCount implements Runnable{
public void run(){
counter=counter+1;//update the counter value
label.setText("the time is "+counter+" seconds");
//your JProgressBar code can go here
//or any other code that you may like
public static void main(String args[]) {

timer_Example form=new timer_Example();


The code is pretty basic but this code can be used to perform various tasks. In the code we initialize the counter to 0 and then create the timer object by calling its constructor and passing it 2 arguments the time in milliseconds after which the timer shall generate an event (timer generates an ActionEvent) and second parameter is an event handler for the action event which in this case is the form object itself.

The actionPerformed function just simply checks whether the count has reached 100 or not and if it has it stops the timer. Otherwise it creates a new runnable object of a nested class updateCount which updates the count value and displays the count value through the JLabel. Here you can do other things like updating the JProgressBar or any other event that you may wish to implement. I have used SwingUtilities.invokeLater() function because it is always recommended that you should place the call to some other class on an event queue and not directly call the class.

I have used a similar concept to develop a simple application in java that performs various operations like Shutdown, Hibernate, Standby, lock etc but in that case the counter is countdown counter. You can also create beautiful application launcher windows with changing backgrounds and updating progress bar with it.

No comments:

Post a Comment