javax.swing.Timer 的用法例程

时间:2023-01-26 20:28:26

写某些程序(比如俄罗斯方块)时需要一个定时触发的事件去触发一段程序的执行,此时就要用到Timer。

javax.swing.Timer的官方文档是这样解释的

public class Timer
extends Object
implements Serializable
Fires one or more ActionEvents at specified intervals. An example use is an animation object that uses aTimer 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 thestart 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 theTimer 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();

现将一个Timer的例程记录下来,仅供参考。

代码:

package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.Timer;

public class Test extends JFrame implements ActionListener {
private int now_s=0;
public Test(){
new Timer(1000,this).start();
while(true);
}

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("now_s="+now_s);
now_s++;
}

public static void main(String[] args){
new Test();
}
}

运行效果:

javax.swing.Timer 的用法例程

(-------完--------)