在JAVA上的Timer中可以停止计时器吗

时间:2018-12-08 19:41:22

标签: java swing timertask swingx

我有一个游戏方法在此方法中包含Timer,仅在某些特定情况下(如果满足以下条件),我想停止计时器...但由于某种原因,它导致我崩溃。

public model() {
public game() {                    
            Timer timer = new Timer(50, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    ....
                   //draw shapes on JFrame

                if (model.Life == 0) { //specific condition
                    model.timer.stop(); //timer is making a crash here
                }
                repaint();
                }
               });
            timer.start();
        }

1 个答案:

答案 0 :(得分:2)

计时器是ActionEvent的来源,因此您可以执行以下操作:

if (your condition)
{
    Timer timer = (Timer)e.getSource();
    timer.stop();
}

这样,您不必担心为Timer保留实例变量。