在 java 中,我有一个程序需要连续检查用户是否按下键。所以在伪代码中,类似
if (isPressing("w"))
{
//do somthing
}
提前致谢!
在java中,您不检查是否按下了键,而是听sKeyEvent
. 实现目标的正确方法是注册 aKeyEventDispatcher
并实现它以维护所需密钥的状态:
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
.
试试这个:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField textField = new JTextField();
textField.addKeyListener(new Keychecker());
JFrame jframe = new JFrame();
jframe.add(textField);
jframe.setSize(400, 350);
jframe.setVisible(true);
}
class Keychecker extends KeyAdapter {
@Override
public void keyPressed(KeyEvent event) {
char ch = event.getKeyChar();
System.out.println(event.getKeyChar());
}
}
我基于@Elist 的方法构建了一个便利实用程序类,它适用于任何键。
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
public class Keyboard {
private static final Map<Integer, Boolean> pressedKeys = new HashMap<>();
static {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(event -> {
synchronized (Keyboard.class) {
if (event.getID() == KeyEvent.KEY_PRESSED) pressedKeys.put(event.getKeyCode(), true);
else if (event.getID() == KeyEvent.KEY_RELEASED) pressedKeys.put(event.getKeyCode(), false);
return false;
}
});
}
public static boolean isKeyPressed(int keyCode) { // Any key code from the KeyEvent class
return pressedKeys.getOrDefault(keyCode, false);
}
}
示例用法:
do {
if (Keyboard.isKeyPressed(KeyEvent.VK_W)) System.out.println("W is pressed!");
} while (!Keyboard.isKeyPressed(KeyEvent.VK_ESCAPE));
你必须实现KeyListener
,看看这里:
http ://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
有关如何使用它的更多详细信息:http: //docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html