2014-09-01 74 views
0

我有一个java swing gui程序,当我点击一个切换按钮时,一个计时器开始,但我想能够点击相同的按钮,计时器停止,现在它不会让我再次点击它。 这是我的定时器类为什么我的按钮不可点击? (爪哇)

public void runningClock(){ 
     isPaused = false; 
     while(!isPaused){ 
     incrementTime(); 
     System.out.println("Timer Current Time " + getTime()); 
     time.setText(""+ getTime()); 
     try{Thread.sleep(1000);} catch(Exception e){} 
     } 
    } 


public void pausedClock(){ 
     isPaused=true; 
     System.out.println("Timer Current Time " + getTime()); 
     time.setText(""+ getTime()); 
     try{Thread.sleep(1000);} catch(Exception e){} 
    } 

,这是我的主类

private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {          

    if(btnRun.getText().equals("Run")){ 
      System.out.println("Run Button Clicked"); 
      btnRun.setText("Pause"); 
      test.runningClock(); 
    } 
    else if(btnRun.getText().equals("Pause")){ 
     System.out.println("Pause Button Clicked"); 
     btnRun.setText("Run"); 
     test.pausedClock(); 

    } 
}     
+0

就拿问题的原因一看[并发在Swing(http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)和[如何使用Swing定时器( http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)为了解决这个问题(如前所述) – MadProgrammer 2014-09-01 23:36:20

回答

5

你冻结Swing事件线程与Thread.sleep(...)while (something)循环。解决方案:不要这么做 - 不要在占用事件线程的事件线程上调用代码,并阻止它执行必要的任务。改为改变程序的状态。并为你的时钟,使用Swing Timer。例如,请看我的答案和代码here

0

你正在你的程序中做这个,​​。由于此声明应用于主线程本身,所以应用程序本身挂起或者可以说冻结。你可以做的是为计时器应用一个单独的线程。

new Thread(new Runnable(){ 
     public void run(){ 
       //Do Stuff 
     } 
}).start();