一、Timer的使用
Timer(int delay, ActionListener listener):创建一个每delay毫秒将通知其侦听器的Timer.
#delay:延迟的毫秒数,0表示启动后立刻执行。
#listener:侦听器对象,可以为null。
javax.swing.Timer的官方文档是这样解释的:
public class Timer extends Object implements Serializable
Fires one or more
二、案例
ActionEvent
s at specified intervals. An example use is an animation object that uses a
Timer
as the trigger for drawing its frames.
Setting up a timer involves creating a Timer
object, registering one or more action listeners on it, and starting the timer using the start
method. For example, the following code creates and starts a timer that fires an action event once per second (as specified by the first argument to the Timer
constructor). The second argument to the Timer
constructor specifies a listener to receive the timer's action events.
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
二、案例
<span style="font-size:14px;">package main;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
* Timer类的使用 在一定的时间段内执行一次指定的对象的方法。
*/
public class Test {
public static void main(String[] args) throws Exception {
ActionListener listener = new TimePrinter();
Timer t = new Timer(1000, listener);
t.start();
JOptionPane.showMessageDialog(null, "退出程序?");
System.exit(0);
}
}
class TimePrinter implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// DateFomat的子类。
System.out.println("现在时刻:" + sdf.format(now));
Toolkit.getDefaultToolkit().beep();
}
}</span>
运行结果:
现在时刻:2016年06月03日 10:21:22
现在时刻:2016年06月03日 10:21:23
现在时刻:2016年06月03日 10:21:24
现在时刻:2016年06月03日 10:21:25
现在时刻:2016年06月03日 10:21:26
现在时刻:2016年06月03日 10:21:27
现在时刻:2016年06月03日 10:21:28
现在时刻:2016年06月03日 10:21:29
现在时刻:2016年06月03日 10:21:30
现在时刻:2016年06月03日 10:21:31
现在时刻:2016年06月03日 10:21:32