展示定时器增量,同时线程停止?Java定时器/计时器任务

huangapple 未分类评论44阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年4月8日 05:28:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/61089681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定