java 计时器线程 Timer类

来源:互联网 发布:淘宝盖楼是什么 编辑:程序博客网 时间:2024/04/28 20:03

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);}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif(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();}}}


0 0
原创粉丝点击