Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
609 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...