如何检查用户是否按了某个键?在java中,我有一个程序需要连续检查用户是否按了一个键。所以在伪代码中,有点像if (isPressing("w")){
//do somthing}提前致谢!
3 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
在Java中,你不检查是否有键被按下,而不是你听到KeyEvent
秒。实现目标的正确方法是注册KeyEventDispatcher
并实现它以维护所需键的状态:
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
。
慕码人2483693
TA贡献1860条经验 获得超9个赞
试试这个:
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());}
添加回答
举报
0/150
提交
取消