如何检查用户是否按下了某个键? [英] How do I check if the user is pressing a key?
本文介绍了如何检查用户是否按下了某个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中,我有一个程序需要不断检查用户是否按下了某个键.所以在伪代码中,类似
In java I have a program that needs to check continuously if a user is pressing a key. So In psuedocode, somthing like
if (isPressing("w"))
{
//do somthing
}
提前致谢!
推荐答案
在 Java 中,您不检查键是否被按下,而是监听KeyEvent
s.实现目标的正确方法是注册一个 KeyEventDispatcher
,并实现它以维护所需键的状态:
In java you don't check if a key is pressed, instead you listen to KeyEvent
s.
The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}
那么你可以随时使用:
if (IsKeyPressed.isWPressed()) {
// do your thing.
}
当然,您可以使用相同的方法来实现 isPressing("<some key>")
,并在 IsKeyPressed
中包含键及其状态的映射.
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
这篇关于如何检查用户是否按下了某个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文