0

我发现在任何使用 Key Listeners 的类中实现的方法包括 keyPressed、keyReleased 和 keyDown,但我如何拥有它以便在按键保持按下状态时连续发生某些事情?意思是有没有办法实现“keyHeld”类型的场景?

4

3 回答 3

2

Don't use a a KeyListener. Swing was designed to be used with Key Bindings.

I have used a Swing Timer for this type of situation as you are now in full control over the repeat rate. You start the Timer with the keyPressed bindings and stop the Timer with the keyReleased binding. The Swing tutorial also has a section on How to Use Timers.

于 2013-03-18T23:19:47.647 回答
1

有两种通用机制。

keyPressed将在按住键时重复调用,直到松开键。但是,在第一次按键和重复按键之间通常会有短暂的延迟。

或者,您可以设置一个标志,表明他们的键已被按下并在释放时重新设置标志。

可能最简单的解决方案是使用某种List包含 al,即当前按下的虚拟键代码。然后,您只需要检查此列表以查看它是否包含您需要使用的虚拟键代码,并在它包含时采取适当的措施。

这导致我警告不要从除事件调度线程之外的任何线程交互或更改任何 UI 组件

于 2013-03-18T21:54:18.377 回答
1

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

s.....ssssssssssssssssssssssssss
于 2013-03-18T21:54:31.070 回答