java 计时器线程 Timer类

java提供了一个很方便的timer类,该类在javax.swing包中。当某些操作需要周期性执行 就可以使用计时器。

我们可以使用Timer类的构造方法Timer(int a,Object b)创建一个计时器,其中参数a的单位是毫秒,确定计时器每隔a

毫秒振铃一次,参数b是计时器的监视器。

计时器创建后,使用Timer类的方法start()启动计时器,即启动线程。使用Timer类的方法stop()停止计时器,即挂起线程,使用restart()重新启动计时器,即恢复线程。

package Example12_12;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example12_12 {
	public static void main(String args[]){
		WindowTime win=new WindowTime();
		win.setTitle("计时器");
	}
}
class WindowTime extends JFrame implements ActionListener{
	JTextField text;
	JButton bStart,bStop,bContinue;
	Timer time;
	SimpleDateFormat m;
	int n=0,start=1;
	WindowTime(){
		time=new Timer(1000,this);
		m=new SimpleDateFormat("hh:mm:ss");
		text=new JTextField(10);
		bStart=new JButton("开始");
		bStop=new JButton("暂停");
		bContinue=new JButton("继续");
		bStart.addActionListener(this);
		bStop.addActionListener(this);
		bContinue.addActionListener(this);
		setLayout(new FlowLayout());
		add(bStart);
		add(bStop);
		add(bContinue);
		add(text);
		setBounds(100,100,320,450);
		validate();
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource()==time){
			Date date=new Date();
			text.setText("时间: "+m.format(date));
			int x=text.getBounds().x;
			int y=text.getBounds().y;
			x=x-1;
			y=y+2;
			text.setLocation(x,y);
		}
		else if(e.getSource()==bStart){
			time.start();
		}
		else if(e.getSource()==bStop){
			time.stop();
		}
		else if(e.getSource()==bContinue){
			time.restart();
		}
		
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值