我有Timer
,其工作原理如下:
public void startTourButton(ActionEvent event) {
new Timer ().schedule(
new TimerTask () {
public void run(){
System.out.println("Going to do something here");
}
}, 0, 5000);
}
我正在尝试从其他Timer
取消event
:
public void stopTourButton(ActionEvent event) {
Timer.cancel();
}
我收到错误
无法从类型Timer
中对非静态方法cancel()进行静态引用
我该如何解决这个问题?
答案 0 :(得分:3)
将计时器保存为类成员,以便稍后取消
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;
}
}
答案 1 :(得分:1)
首先声明一个变量,然后实例化它,然后将其用作参考:
Timer myTimer;
public void startTourButton(ActionEvent event) {
myTimer = new Timer ().schedule(
new TimerTask () {
public void run(){
System.out.println("Going to do something here");
}
}, 0, 5000);
}
public void stopTourButton(ActionEvent event) {
myTimer.cancel();
}