0

How do I make my Escape key pause and resume a game when it is pressed twice? I have tried calling the key adapter class in my thread class but it only pauses the game; it does not resume it.

Here is the code that pauses the game:

//the thread class
class recMove extends Thread {
    JFrame b;

    public boolean running=true;

    //public boolean gameover=false;
    public recMove(JFrame b){
        this.b=b;
        pauseGame();
    }

    public void run(){
        while(running){
            b.repaint();
            try {
               Thread.sleep(100);
            } catch(InterruptedException e){}
        }
   }

   public void pauseGame(){
       addKeyListener(new KeyAdapter(){
           public void keyPressed(KeyEvent e) {
              int keyCode=e.getKeyCode();
              if(keyCode==KeyEvent.VK_ESCAPE) {
                  running=false;
                  System.out.println("escape pressed");
              }
              if(keyCode==KeyEvent.VK_END){
                  System.exit(0);
              }
          }
      });
   }
}
Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
  • Start by using an `AtomicBoolean` instead of a plain `boolean`. You should also have a inner pause lock which will cause the main loop to wait within it until your resume the game, unless you intend to stop it. Maybe something like [this for example](http://stackoverflow.com/questions/31715950/control-of-running-thread-using-multiple-threading-concept-of-java/31716210#31716210) – MadProgrammer Aug 04 '15 at 03:56
  • thanks much, don't know much about that but I will definitely look into it. – BlueWizAngel Aug 04 '15 at 04:00

1 Answers1

0

It doesn't resume because the thread is killed, when you press escape the running value is set to false therefore this loop:

while(running){
    b.repaint();
    try {
       Thread.sleep(100);
    } catch(InterruptedException e){}
}

Will end, which in turn will make the run() method exit. When a run() method of a class extending Thread (or implementing Runnable) exits that thread is being killed so there's nothing more listening for your keypresses.

You need to change your run() logic so it doesn't exit when running is set to false but instead wait for the next keypress or add the listener somewhere else (in a different thread) so it will create a new thread with the game again.

Furthermore in your logic esc only changes running to false, if you want it to then resume the game you should check the state of running and if it's false you should set it to true instead.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
  • Please can you also help me with this............http://stackoverflow.com/questions/31776720/how-to-make-all-my-bullets-remove-intersected-objects – BlueWizAngel Aug 04 '15 at 04:10