简体   繁体   English

如何停止Swing定时器?

[英]How to stop a Swing Timer?

i have a problem in my code, because i cant stop the swing.timer 我的代码有问题,因为我无法停止swing.timer

//some code here //一些代码

I tried to put a if statement but it doesnt working. 我试图放一个if语句,但是它不起作用。

Static int gScore = 1000;
t = new Timer(100, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        score01.setText("score: " + gScore);
        gScore--;     
    }
});
t.start();
t.setRepeats(true);
if(gScore== 970){//A
    t.stop();
    t.setRepeats(false);    
}//A

i want to stop the timer when it reach to a given value and remove it inside the JFrame 我想在达到给定值时停止计时器,并在JFrame中将其删除

Your timer shall be final 您的计时器是最终的

t.cancel();
t.purge();

and when declaring your timer, set it as final 并在声明计时器时将其设置为最终计时器

final Timer t = new Timer(...)

You should change your code as followed: 您应该按照以下步骤更改代码:

static int gScore = 1000;
final Timer t = new Timer(100, new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    score01.setText("score: " + gScore);
    gScore--;
    if(gScore== 970){//A
      t.stop();
    }//A
  }
});
t.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM