java秒表/计时器实现

来源:互联网 发布:wind资讯经济数据终端 编辑:程序博客网 时间:2024/05/17 09:00

使用java.util.Timer;java.util.TimerTask类

/*date:2013/06/13 * author:idevcod@163.com * */import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Timer;import java.util.TimerTask;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JLabel;public class time extends JFrame implements ActionListener{private Timer timer=new Timer();private JPanel time_panel=new JPanel();private JLabel time_label=new JLabel("test");private JButton start_button=new JButton("开始"),pause_button=new JButton("暂停");private boolean is_pause=false;private timetask mytimetask=new timetask();private int hh,mm,ss;public time(){setLayout(null);setBounds(100,100,400,200);time_panel.setBounds(0, 0, 100, 200);time_label.setBounds(100, 0, 100, 200);start_button.addActionListener(this);pause_button.addActionListener(this);time_panel.add(start_button);time_panel.add(pause_button);time_panel.setBackground(Color.CYAN);time_label.setBackground(Color.black);add(time_panel);add(time_label);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer.scheduleAtFixedRate(mytimetask, 0, 1000);//timer}class timetask extends TimerTask{private int count_time=0;private String date;@Overridepublic void run() {// TODO Auto-generated method stubif(!is_pause){count_time++;hh=count_time/3600;mm=(count_time%3600)/60;ss=count_time%60;//System.out.println(count_time);date=hh+":"+mm+":"+ss;time_label.setText(date);}}}public static void main(String[] args){new time();}@Overridepublic void actionPerformed(ActionEvent key) {// TODO Auto-generated method stubif(key.getSource()==pause_button) {if(!is_pause){is_pause=true;pause_button.setText("继续");}else{is_pause=false;pause_button.setText("暂停");}}else if(key.getSource()==start_button){is_pause=false;}}}


原创粉丝点击