0

Im using Netbeans 8.0, and Im having difficult on stopping the timer I made in my GUI. Heres my code.

public class Task1 implements Runnable{
    public void run()
    {
        long start = System.currentTimeMillis();
        while (!Thread.interrupted())
        {
            long time = System.currentTimeMillis() - start;
            final long seconds = time / 1000;
            final long min = seconds / 60;
            final long remainingSec = seconds % 60;
            final long hr = min / 60;
            SwingUtilities.invokeLater(new Runnable() {
                 public void run()
                 {
                       jLabel3.setText("Time Passed: " + hr + ":" + min + ":" + remainingSec);
                 }
            });
           try { Thread.sleep(100); } catch(Exception e) {  }
        }
    }

}
Thread t1 = new Thread(new Task1());
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    t1.start();
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    t1.interrupt(); // this one doesnt stop my timer.
    } 

I made two buttons which the jButton1 starts the timer and the jButton2 stops the timer. Please advice.

kersey
  • 137
  • 1
  • 1
  • 11
  • This might explain why it doesn't work: http://stackoverflow.com/q/3590000/535275 – Scott Hunter Oct 17 '14 at 17:29
  • Actually, I see a lot of problems. First, `actionPerformed(ActionEvent)` should not have anything before it. You don't even implement `ActionListener`, so I'm not sure why you're declaring those methods. You also didn't show us where you add the listeners to the buttons. Please provide a [MCVE](http://stackoverflow.com/help/mcve) of your problem – Vince Oct 17 '14 at 17:29
  • @VinceEmigh I was thinking of fernando's answer on this link: http://stackoverflow.com/questions/19894607/java-how-to-stop-thread that just by calling .kill() method inside my button action event, it would stop my timer, which on my part based on scanning on other question on this forum I would just use .interrupt(). Im not also good in java thats why Im asking help, and it took me difficult to accomplish to make a timer and show it on a jlabel. Hope you understand. – kersey Oct 17 '14 at 17:48
  • hmmm... @ScottHunter ur advice gives me my answer, I just change my catch event into this *catch(InterruptedException e) { break; }* as suggested by Evgeni and my stop button now works :D – kersey Oct 17 '14 at 17:59

0 Answers0