java秒表/计时器实现

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

/*date:2013/06/13
 * author:[email protected]
 * */
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;
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(!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();
	}
	@Override
	public void actionPerformed(ActionEvent key) {
		// TODO Auto-generated method stub
		if(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;
		}
	}
}


你可能感兴趣的:(源代码)