/** Creates key listeners which issue requests to the simulation. */ public void addListeners(final Display2D display) { final PacMan pacman = (PacMan) state; final SimpleController cont = (SimpleController) controller; // Make us able to take focus -- this is by default true usually anyway display.setFocusable(true); // Make us request focus whenever our window comes up displayFrame.addWindowListener( new WindowAdapter() { public void windowActivated(WindowEvent e) { display.requestFocusInWindow(); } }); // the display frame has just been set visible so we need to request focus once display.requestFocusInWindow(); display.addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int c = e.getKeyCode(); switch (c) { case KeyEvent.VK_UP: pacman.actions[0] = Pac.N; break; case KeyEvent.VK_DOWN: pacman.actions[0] = Pac.S; break; case KeyEvent.VK_LEFT: pacman.actions[0] = Pac.W; break; case KeyEvent.VK_RIGHT: pacman.actions[0] = Pac.E; break; case KeyEvent.VK_W: pacman.actions[1] = Pac.N; break; case KeyEvent.VK_S: pacman.actions[1] = Pac.S; break; case KeyEvent.VK_A: pacman.actions[1] = Pac.W; break; case KeyEvent.VK_D: pacman.actions[1] = Pac.E; break; case KeyEvent .VK_R: // Reset the board. Easiest way: stop and play, which calls start() cont.pressStop(); cont.pressPlay(); break; case KeyEvent.VK_P: // Pause or unpause the game cont.pressPause(); break; case KeyEvent.VK_M: // Call forth MASON's new simulation window if (cont.getPlayState() != cont.PS_PAUSED) // pause it! cont.pressPause(); cont.doNew(); // the MASON window belongs to our frame, so Java stupidly doesn't send // us a window activated event when the MASON window is closed and our // frame comes to the fore again. So we have to manually do request // focus again here. display.requestFocusInWindow(); break; default: // do nothing break; } } }); }