简体   繁体   English

KeyAdapter在java中被卡住了一秒钟

[英]KeyAdapter gets stuck for a second in java

I'm making a simple game in java, and I'm making the movement with keys using a key adapter. 我在java中制作一个简单的游戏,我正在使用键适配器进行键盘移动。 It works fine, but when I switch direction, the player goes one pixel in the new direction, then stops for a moment and then goes fine (you know, when you press a letter on your keyboard, and it writes one letter, but if you hold it, after a moment it will start to flow). 它工作正常,但当我切换方向时,播放器在新方向上移动一个像素,然后停一会儿然后就好了(你知道,当你按下键盘上的一个字母时,它写了一个字母,但是如果你拿着它,过了一会儿它会开始流动)。 Is there any way to fix this? 有没有什么办法解决这一问题? Or should I use a key listener instead? 或者我应该使用密钥监听器吗?

A better way would be to have a boolean such as movingRight for each of the directions. 更好的方法是为每个方向设置一个布尔值,例如movingRight Initially movingRight = false . 最初movingRight = false In keyPressed() , check whether or not the right arrow (or D or whatever key) was pressed and set movingRight = true if so. keyPressed() ,检查是否按下右箭头(或D或任何键),如果是,则设置movingRight = true In keyReleased() , do the same but set the boolean to false if the relevant key was released. keyReleased() ,如果相关键被释放,则执行相同操作但将布尔值设置为false。 Then in your main update loop, move the player one pixel to the right if movingRight == true , and so forth for each of the directions. 然后在主更新循环中,如果movingRight == true ,则向右移动播放器一个像素,依此类推每个方向。

To reiterate, this eliminates the small lag because it doesn't rely on keypress events, but rather just makes sure the key has been pressed and has not yet been released (and so we know it is being held down). 重申一下,这消除了小的延迟,因为它不依赖于按键事件,而只是确保按键已被按下并且尚未被释放(因此我们知道它被按下)。

Personally i would use keyListeners, They work best for me. 我个人会使用keyListeners,他们最适合我。

Try making a simple method to check witch key was pressed and then have it move the JLable to a position on the window eg 尝试制作一个简单的方法来检查是否按下了女巫键,然后让它将JLable移动到窗口上的位置,例如

public static void moveUp()
{
     int x;
     int y;
     x = NewJFrame.playerJLabel.getX();
     y = NewJFrame.playerJLbale.getY();

     y = y + 10;

     NewJFrame.playerJLable.setLocation(x, y);
}

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

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