在java中怎么通过按钮实现一个计时器功能!
最好能举一个例子!
谢谢各位了 !

解决方案 »

  1.   

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import java.text.*;import javax.swing.*;public class Clock extends JFrame implements ActionListener,Runnable { JButton b1 = new JButton("计时开始");
    JButton b2 = new JButton("计时结束");
    JPanel p=new JPanel();
    TextField tf = new TextField(10);
    Thread t;
    Date d1;
    Date d2;
    public  Clock() {
    p.add(b1);
    p.add(b2);
    p.add(tf);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setContentPane(p);
    this.setTitle("计时器");
    this.setSize(400,200);
    this.setVisible(true);
    b1.addActionListener(this);
    b2.addActionListener(this);
    } public void run() {
    while (true) {
    try {
    t.sleep(1);
    } catch (InterruptedException e) {
    }
    d2 = new Date();
    tf.setText(new Long((d2.getTime()-d1.getTime())).toString()+"毫秒");
    }
    } public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(b1))
    {
    t=new Thread(this);
    t.start();
    b1.setEnabled(false);
    b2.setEnabled(true);
    d1=new Date();
    tf.setText("");
    }
    else{
    b1.setEnabled(true);
    b2.setEnabled(false);
    if(t!=null){
    t.stop();
    }
    }
    }
    public static void main(String[] args){
    new Clock();
    }
    }