简体   繁体   中英

Pausing and resuming swing Timer

I want to pause and resume my snake game when I hit space button.

if (keyCode == KeyEvent.VK_SPACE) {
    timer.stop();
}

if (keyCode == KeyEvent.VK_ENTER ) {
    timer.start();
}

I've done this but to resume the game I need to hit "Enter" any idea?

I've done this but to resume the game I need to hit "Enter" any idea?

You can use the same KeyStroke to stop/start the Timer. Just check the status of the Timer:

if (timer.isRunning())
    timer.stop();
else
    timer.start();

Also, don't use a KeyListner for this. You should be using Key Bindings to map a KeyStroke to an Action .

@retatu thanks for the idea i found the solution i just needed to initialize the locker in the constructor like that

public Controller(Snake snake,View view) {
    this.snake = snake;
    this.view = view;
    locker = false;
}

and then use it in the code

if (keyCode == KeyEvent.VK_SPACE ){
        if(!locker){
            view.timer.stop();
            locker=true;
        }else{
            locker = false;
            view.timer.start();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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