带有acm.graphics的关键侦听器 [英] key listener with acm.graphics

查看:69
本文介绍了带有acm.graphics的关键侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题有关 a>.

我在 ACM图形库中构建了一个游戏.我希望能够在按 P键时暂停游戏.但是,我查看了文档,似乎简短地提到了关键侦听器,但是在这种情况下并没有使用它们的实际示例(除非我错过了一些内容).

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

我不想使用控制台或对话框,因为我不想通过键盘输入数据,我只想能够使用来打开和关闭我的暂停方法我的主游戏循环中的 P键.这可能吗?

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?

推荐答案

您需要一个将ACM Program子类化的类,以向其添加键侦听器.其次,您需要一个实现KeyListener的类(可能是同一类),然后在KeyListener#keyPressed中进行代码.您可以通过KeyEvent.getKeyCode获取所按键的代码,并检查其是否等于所需键(在这种情况下为P键).

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

这篇关于带有acm.graphics的关键侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆