英文:
Showing timer increments while the thread stops? Java timer / timertask
问题
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);
英文:
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);
专注分享java语言的经验与见解,让所有开发者获益!
评论