简体   繁体   English

Java Swing中的键盘“暂停”事件?

[英]Keyboard “Held” Event in Java Swing?

I found the methods to implement in any class that uses Key Listeners include keyPressed, keyReleased and keyDown, but how do I have it so that something happens continuously while the key remains pressed? 我发现可以在任何使用键侦听器的类中实现的方法包括keyPressed,keyReleased和keyDown,但是我如何拥有它,以便在保持按下键的同时连续发生某些事情? Meaning is there a way to implement a "keyHeld" type scenario? 意味着有一种方法可以实现“ keyHeld”类型的场景吗?

Don't use aa KeyListener. 不要使用KeyListener。 Swing was designed to be used with Key Bindings . Swing被设计为与键绑定一起使用。

I have used a Swing Timer for this type of situation as you are now in full control over the repeat rate. 我已经使用了Swing Timer来处理这种情况,因为您现在可以完全控制重复率。 You start the Timer with the keyPressed bindings and stop the Timer with the keyReleased binding. 您可以使用keyPressed绑定启动计时器,并使用keyReleased绑定停止计时器。 The Swing tutorial also has a section on How to Use Timers. Swing教程还包含有关如何使用计时器的部分。

There are two general mechanisms. 有两种通用机制。

keyPressed will be repeatedly called while the key is held down, until the key is released. 按住键时,将反复调用keyPressed ,直到释放键为止。 There is, however, normally a short delay between the first key press and repeat key. 但是,通常在第一次按键和重复按键之间会有短暂的延迟。

Alternatively, you could set a flag that indicates that they key has bee pressed and resettle flag when it is released. 另外,您可以设置一个标志,指示他们已按下蜜蜂键,并在释放时重新设置标志。

Probably the easiest solution for this would be to use some kind of List the contains al, the virtual key codes that are currently pressed. 对此,最简单的解决方案可能是使用某种“ List ”包含当前按下的虚拟键代码。 You would then just need to check this list to see if it contains the virtual key code you need to work with and take appropriate action when it does. 然后,您只需要检查此列表以查看它是否包含您需要使用的虚拟键代码,并在操作时采取适当的措施。

This leads me to the warning of, don't interact or change any UI component from any thread other then the Event Dispatching Thread 这导致我发出警告,不要交互或更改事件调度线程以外的任何线程的UI组件

keyTyped方法在按下键时连续调用,但有一个初始延迟:

s.....ssssssssssssssssssssssssss

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM