javax.swing.Timer 的用法例程

写某些程序(比如俄罗斯方块)时需要一个定时触发的事件去触发一段程序的执行,此时就要用到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 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();

现将一个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();
	}
}

运行效果:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值