Search code examples
javakeyboardkeyboard-eventskeylisteneracm.graphics

key listener with acm.graphics


Somewhat related to this question.

I have a game built in the ACM Graphics Library. I want to be able to pause the game upon a keypress of the P key. However I've looked in the documentation and there seems to be a mention of key listeners briefly but no actual examples of them in use in this context (unless I've missed something).

I don't want to use a console or dialogue box as I don't want to enter data via the keyboard, I just want to be able to toggle my pause method on and off using the P key within my main game loop. Is this possible?


Solution

  • You need a class that subclasses ACM's Program to add a key listener to. Secondly, you need a class that implements KeyListener (this could be the same class) and then do your code in KeyListener#keyPressed. You can get the pressed key's code via KeyEvent.getKeyCode and check whether it equals your desired key (in this case the P key).

    The following example illustrates how this may work. It didn't test it, but it should do the trick.

    public class KeyListenerExample extends GraphicsProgram {
    
        @Override
        public void run() {
            addKeyListeners(new MyKeyListener());
        }
    
        private class MyKeyListener implements KeyListener {
    
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_P) {
                    System.out.println("Key 'P' has been pressed!");
                }
            }
    
            @Override
            public void keyReleased(KeyEvent e) { /* Empty body */ }
    
            @Override
            public void keyTyped(KeyEvent e) { /* Empty body */ }
    
        }
    }
    

    It would be helpful if you could provide a Minimal, Complete, and Verifiable example for your question (especially for further questions).