2014-09-01 2 views
0

나는 자바 스윙 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

문제의 원인에 대한 [스윙의 동시성 (http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)를 살펴보고 [스윙 타이머를 사용하는 방법 (http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) 멀리 그것을 해결하기 위해 (이미 언급 한 바와 같이) – MadProgrammer

답변

5

당신은 당신의 Thread.sleep(...)while (something) 루프와 스윙 이벤트 스레드를 동결하고이다. 해결책 : 그렇게하지 마십시오. 이벤트 스레드를 차지하는 이벤트 스레드에서 코드를 호출하여 필요한 작업을 수행하지 못하게하십시오. 대신 프로그램의 상태을 변경하십시오. 그리고 시계에는 Swing Timer을 사용하십시오. 예를 들어 내 대답을보고 here을 입력하십시오.

0

프로그램에서이 작업을 수행하고 있습니다 (try{Thread.sleep(1000);} catch(Exception e){}). 이 문은 주 스레드 자체에 적용되므로 응용 프로그램 자체가 중지되거나 고정 될 수 있습니다. 타이머에 별도의 스레드를 적용하면됩니다.

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