[英]How to detect release of a keystroke using Java Swing?
I am having some issues getting some code to work that detects release of a keystroke. 我遇到了一些问题,需要一些代码来检测击键的释放。 I am writing a video game, and I would like to iniitate the movement of an icon with the press of a key, and terminate the movement once the key has been released.
我正在编写一个视频游戏,我想通过按一个键来启动图标的移动,并在释放键后终止该移动。 I have read other people's postings on this, and they seem to say the way to handle this is to set a flag in the keyReleased code that would terminate the movement I assume you would have initiated in the keyPressed code.
我已经阅读了其他人的相关帖子,他们似乎说,解决此问题的方法是在keyReleased代码中设置一个标志,该标志将终止移动(假定您将在keyPressed代码中发起)。 However, I assume you would have to put a Thread.Sleep into the KeyPressed code in order to allow the KeyReleased code to fire (which would set the flag)?
但是,我假设您必须将Thread.Sleep放入KeyPressed代码中才能触发KeyReleased代码(这将设置标志)? Otherwise control would never return to the dispatch loop from the KeyPressed code?
否则控件将永远不会从KeyPressed代码返回到分派循环?
Anyway, here is the code I can not get to work that should pickup the release of key 'a'. 无论如何,这是我无法使用的代码,应该拿起键“ a”的释放。
MoveGunLeftActionReleased aKeyActionReleased= new MoveGunLeftActionReleased(); MoveGunLeftActionReleased aKeyActionReleased = new MoveGunLeftActionReleased();
… …
… …
statusPanel.getInputMap().put(KeyStroke.getKeyStroke("released a"), "aCharKeyReleased");
statusPanel.getActionMap().put("aCharKeyReleased", aKeyActionReleased);
… … ……
static class MoveGunLeftActionReleased extends AbstractAction
{
public void actionPerformed(ActionEvent rf) {
System.out.println("RELEASED");
aKeyReleased= true;
}
}
The object: aKeyActionReleased never executes. 对象:aKeyActionReleased永远不会执行。
What am I doing wrong? 我究竟做错了什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.