gpt4 book ai didi

java - 从单独的方法关闭计时器

转载 作者:行者123 更新时间:2023-12-01 18:03:17 25 4
gpt4 key购买 nike

我有一个计时器,其工作原理如下:

public void startTourButton(ActionEvent event) {
new Timer ().schedule(
new TimerTask () {

public void run(){
System.out.println("Going to do something here");
}

}, 0, 5000);

}

我正在尝试从此处的不同事件取消计时器:

public void stopTourButton(ActionEvent event) {
Timer.cancel();
}

我收到错误

Cannot make a static reference to the non-static method cancel() from the type Timer

我该如何解决这个问题?

最佳答案

将计时器保存为类(class)成员,以便稍后可以取消

class YourClass {

Timer timer;

public void startTourButton(ActionEvent event) {
if (timer == null) {
timer = new Timer();
}
timer.schedule(
new TimerTask () {
public void run(){
System.out.println("Going to do something here");
}
}, 0, 5000);
}
}

public void stopTourButton(ActionEvent event) {
timer.cancel();
timer = null;
}
}

关于java - 从单独的方法关闭计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com