检测在java 7中按下的键 [英] Detect a key being held down in java 7

查看:126
本文介绍了检测在java 7中按下的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按键绑定 a d 键以使角色左右移动,但按键时只会发生一次动作。如何在 a d 被按下时修改此代码以使其执行此事件?

I'm trying to key bind the a and d keys to make a character move left and right, but the actions only happen once when you press the keys. How can I modify this code to make it do the event while a or d is being held down?

p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0),"up");
p.getActionMap().put("up", new UpAction());
p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
p.getActionMap().put("left", new LeftAction());
p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
p.getActionMap().put("right", new RightAction());
p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),"quit");
p.getActionMap().put("quit", new StopAction());


推荐答案

收听两个独立的事件,其中一个事项是关键是压下,另一个被释放。

Listen for two separate events, one where the key is pressed down, the other where it is released.

按键应该设置一个标志,释放它清除标志。然后你可以检查标志的值,而不是不断尝试纠缠键盘。
当您查看的不仅仅是一个键时,您需要将所有当前按下的KeyStrokes存储在地图中。

Pressing the key should set a flag, releasing it clear said flag. Then you can check the value of the flag instead of continually trying to pester the keyboard. When you're looking at more than just one key, you'd want to store all of the currently pressed KeyStrokes in a map.

这篇关于检测在java 7中按下的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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