一、Timer的使用
Timer(int delay, ActionListener listener):創建一個每delay毫秒將通知其偵聽器的Timer.
#delay:延遲的毫秒數,0表示啓動後立刻執行。
#listener:偵聽器對象,可以爲null。
javax.swing.Timer的官方文檔是這樣解釋的:
public class Timer extends Object implements Serializable
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