Construction method: Timer (int delay,actionlistener listener)
Create a Timer that notifies its listeners every delay millisecond.
A sample code for the API
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay,taskPerformer).start();
The code creates and initiates a timer that fires an action event per second (as specified by the first parameter of the timer construction method). The second parameter of the timer construction method specifies a listener that receives the Timer action event.
The API above shows that Javax.swing.Timer often use timer in GUI programming when component content is updated, such as JTable, JLabel content updates.
The following is a simple GUI program that shows the time and can deepen the understanding of the use of the timer:
Swing program code to show time
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import javax.swing.JFrame;
import Javax.swing.JLabel;
Import Javax.swing.Timer;
/**
* Test the use of timer in swing
* A display time GUI program
* @author wasw100
*
*/
public class Timertest Extends JFrame implements ActionListener {
//A display time JLabel
Private JLabel jltime = new JLabel ();
private timer timer;
Public timertest () {
Settitle ("Timer test");
Setdefaultcloseoperation (Jframe.exit_on_close);
SetSize (180,80);
Add (jltime);
//Set timer timer and start
Timer = new timer (500,this);
Timer.start ();
SetVisible (TRUE);
}
/**
* Execution of the part that the timer is to perform,
*/
@Override
public void actionperformed (ActionEvent e) {
DateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Date date = new Date ();
Jltime.settext (Format.format (date));
}
public static void Main (string[] args) {
new timertest ();
}
}
Program Description:
class implements the ActionListener interface, so you can direct the timer = new timer (500,this) and use this to initialize the timer.
When the timer is started (Timer.start ()), the Actionperformed method body of the implemented ActionListener interface is executed every 500 milliseconds
Here's a little bit more information to show the time format:
DateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
MM represents the month mm for minutes Hh:12 hour system display several hh:24 hour system display points