Friday, 14 August 2015

How To Use Swing Timers In Swing Applications

In this example we will see how to use swing timers in your GUI programs.Don't be consider these  timers as a java.util.Timer because swing timers are used for GUI related task as I have used in below program while other timer are used for general purpose.

USES OF SWING TIMERS:

Following are the ways in which swing timers can be used
  • It can be used to perform a specific task after some delay.
  • It can also be used to perform a task repeatedly.

CODING:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class myframe extends JFrame implements ActionListener
{
int time ;
JLabel l1;
Timer mytimer;

myframe()
{
time = 60;
setTitle("J Timer");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1 = new JLabel("TIMER");
add(l1); 
mytimer = new Timer(1000,this);
mytimer.setInitialDelay(1000);
mytimer.start();
setSize(700,350);
setVisible(true);
}   

public void actionPerformed(ActionEvent eve)
{
time--;
if(time>0)
{
l1.setText("Time : "+time+"sec");
}else
{
l1.setText("Timer Stop");
mytimer.stop();
}
}
}

class timer 
{


public static void main(String[] args) 
{

myframe x = new myframe();
}
}


OUTPUT:


No comments:

Post a Comment