Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...