简体   繁体   中英

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. 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. Initially movingRight = false . In keyPressed() , check whether or not the right arrow (or D or whatever key) was pressed and set movingRight = true if so. In keyReleased() , do the same but set the boolean to false if the relevant key was released. 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.

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.

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

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

     y = y + 10;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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