0

I'm trying to design a stopwatch that stops according to an amount of seconds that a user puts in through a GUI. I would like to be able to show each second go by in a label, which currently works only if I remove any limit on when to stop the timer. But if I add a code that stops the timer after the desired elapsed time, the code runs as is, and the timer does stop after the specified time, but doesn't show each increment in the "secondsJLabel" label, that shows each second elapsing. Part of me wonders if there can be another code running at the same time that just waits and checks for the seconds to elapse to be equal to the user-input amount of seconds, and then executes when it is equal. But I just don't how to search for what I need.

This is not for school, but a personal project. Open to any and all criticism, as I'm new to coding. Is this even how you do a timer?

Here is the code from my "go" button.

long timeToStop = Integer.parseInt(desiredTimeJTextField.getText()); 

TimeKeeper myKeeper = new TimeKeeper();
TimerTask task = new TimerTask()      
{
    public void run()
    {
        secondsPassed++;
        secondsJLabel.setText(Integer.toString(secondsPassed));
    }
};
myKeeper.start(task);
try{
    Thread.sleep(timeToStop*1000);
} catch (InterruptedException exc){}
myKeeper.stop(task);
napentathol
  • 1,583
  • 2
  • 13
  • 15
Jonathan
  • 1
  • 1
  • Don't use a TimerTask. Don't use Thread.sleep(). See: https://stackoverflow.com/questions/7816585/program-freezes-during-thread-sleep-and-with-timer/7816604#7816604 for a simple example that demonstrates how to use a Swing Timer. For your example you would want to have a counter for the number of seconds to count down. Each time the Timer generates an event you subtract one from the variable. If the variable is 0, you then stop the Timer. – camickr Apr 07 '20 at 22:18
  • Okay thanks! I'll check it out, experiment and report back. – Jonathan Apr 08 '20 at 02:20
  • @camickr I got it working! Thank you so much – Jonathan Jul 03 '20 at 17:26

0 Answers0