简体   繁体   English

游戏计时器不会停止

[英]Game timer won't stop

I am trying to set a timer to randomly set the frame in the screen, but then, depending on the boolean , set it back to normal. 我试图设置一个计时器来随机设置屏幕中的帧,但是然后根据boolean ,将其设置回正常状态。 I have already tried .cancel() but it doesn't work. 我已经尝试过.cancel()但是不起作用。 How could I stop this timer?: 我如何才能停止此计时器?:

if(e.getSource()==impossible){

            impossiblity=!impossiblity;
            System.out.println(impossiblity);
            if(!impossiblity){
                new Timer().schedule(new TimerTask() {
                    public void run()  {
                        int randWidth=(int)((dim.width-gameFrame.getSize().width) * Math.random());
                        int randHeight=(int)((dim.height-gameFrame.getSize().height) * Math.random());
                        gameFrame.setLocation(randWidth, randHeight);//sets location to center
                    }
                }, 1000, 1000);
            } else gameFrame.setLocation(dim.width/2-gameFrame.getSize().width/2, 0);//sets Location to center of screen
        } 

right now it does set the gameframe back to normal but then goes right back to randomizing 现在它确实将游戏框架设置为正常,但随后又回到随机

In general trying to cancel timers or other threads from outside the thread is a bad idea and leads to all sorts of problems. 通常,尝试从线程外部取消计时器或其他线程是一个坏主意,并且会导致各种问题。

Your best bet is to set some sort of flag or counter that the TimerTask checks when it comes to run. 最好的选择是设置某种标志或计数器,以便TimerTask在运行时进行检查。

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

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