一个简单的计时器:
public class Testtime extends JFrame implements ActionListener,Runnable{
JButton btn1;
JButton btn2;
JLabel time;
int minute,seconds;
Thread begin;
boolean flag;
public Testtime(){
btn1=new JButton("开始计时   ");
btn2=new JButton("   停止计时");
time=new JLabel(0+":"+0);
minute=0;seconds=0;
add(btn1);
add(time);
add(btn2);
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
btn1.addActionListener(this);
btn2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1){
begin=new Thread(Testtime.this);
minute=0;seconds=0;
            flag=true;
begin.start();
}
else{
flag=false;

}

}
public void run(){
while(flag){
seconds++;
if(seconds%60==0){
seconds=0;
minute++;
}
time.setText(minute+" : "+seconds);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]){
new Testtime();
}
}
点击按钮“开始计时”,“停止计时”均能正常工作。但是如果我连续点击了两次“开始计时”,秒钟速度会快一倍。
请问该怎么修改代码呢?

解决方案 »

  1.   

    begin=new Thread(Testtime.this);
    把这行代码放在方法外面去,因为你点一次就创建了一个线程,当然你的速度会变快,因为已经有两个线程在及时了,放在外面就应该没问题了
      

  2.   

    事件处理里面,需要判断当前线程是否还是alive的,如果是则将其停止。
    如下修改代码:  public void actionPerformed(ActionEvent e) {
          if(e.getSource()==btn1){
              if (begin != null && begin.isAlive()) {  //检查线程的状态
                begin.stop();
              }
              begin = new Thread(Testtime.this);
              
              minute=0;seconds=0;
              flag=true;
              begin.start();
          }
          else{
              flag=false;
          }
      }
      

  3.   

    可是我要的是,每次点btn1都可以开始这个线程,如果放外面的话,这个程序就只能进行一次
      

  4.   

    那你就加个判断喽,如果flag为true就啥都不干。否则把flag设置为true再启动线程。