问题
I wasn't quite sure how to word the title of this question. Basically I'm making space invaders with JFrames, and using KeyBindings for keyboard input. The keybindings work fine, and I can move the ship around without a problem. However, if I hold down a key, the ship moves 5 pixels and then pauses for about half a second, after which it moves smoothly. When the key is pressed, my code increases the ship's speed (which moves the ship by 5-10 pixels every frame). I'm assuming this is a common and normal behaviour of keyboard input, but I want the ship to move consistently smoothly. Is there a way to achieve this?
(Note. My code is very long, and since I'm assuming this is a normal thing to happen, I won't post it straight away. However, if you do need to see it, leave a comment and I'll edit it in.)
回答1:
The delay is OS dependent. Each OS defines its own "repeat rate" for generating events when a key is held down.
The secret is to start a Swing Timer when the key is pressed and then used the Timer to generate an events to do the animation and then stop the Timer when the key is released. This way you can control the animation interval independent of the OS.
Check out Motion Using the Keyboard. The KeyboardAnimation
example code shows one way you could do this.
来源:https://stackoverflow.com/questions/25045438/java-keybindings-input-delay