Java键绑定输入延迟 [英] Java KeyBindings input delay

查看:71
本文介绍了Java键绑定输入延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定该问题标题的字眼.基本上,我正在使用JFrames进行空间入侵,并使用KeyBindings进行键盘输入.键绑定工作正常,我可以毫无问题地移动船.但是,如果我按住一个键,飞船将移动5个像素,然后暂停约半秒钟,然后平稳移动.当按下键时,我的代码会提高飞船的速度(每帧将飞船移动5-10像素).我假设这是键盘输入的一种常见且正常的行为,但是我希望飞船能够始终如一地平稳移动.有没有办法做到这一点?

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.)

推荐答案

延迟取决于操作系统.每个操作系统都定义自己的重复率",以便在按住某个键时生成事件.

The delay is OS dependent. Each OS defines its own "repeat rate" for generating events when a key is held down.

秘诀在于,当出现以下情况时,启动 Swing Timer 按下该键,然后使用计时器生成事件以制作动画,然后在释放键时停止计时器.这样,您可以独立于操作系统来控制动画间隔.

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.

查看使用键盘运动. KeyboardAnimation示例代码显示了您可以执行此操作的一种方法.

Check out Motion Using the Keyboard. The KeyboardAnimation example code shows one way you could do this.

这篇关于Java键绑定输入延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆