0

I have a java swing gui program and when I click a toggle button a timer begins but I want to be able to click the same button and the timer stops and right now it won't let me click on it again. This is in my timer class

 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){}
   }

and this is in my main class

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();

    }
}                   
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
John
  • 75
  • 1
  • 2
  • 11
  • Take a look at [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for the cause of the problem and [How to use Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for a away to fix it (as has already been mentioned) – MadProgrammer Sep 01 '14 at 23:36

2 Answers2

5

You're freezing the Swing event thread with your Thread.sleep(...) and while (something) loops. Solution: don't do that -- don't call code on the event thread that occupies the event thread and prevents it from doing its necessary tasks. Instead change the state of your program. And for your clock, use a Swing Timer. For example, please look at my answer and code here.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

You are doing this in your program, try{Thread.sleep(1000);} catch(Exception e){}. As this statement is applied on the main thread itself, so the application itself hangs or you can say freezes. What you can do is apply a separate thread for the timer.

 new Thread(new Runnable(){
         public void run(){
              //Do Stuff
         }
 }).start();
gprathour
  • 14,813
  • 5
  • 66
  • 90