Sign in to follow this  

[java] keylistener

This topic is 3483 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, i want to make an image move on a key press, everything works fine but i want to not listening any keypress while moving. thankyou

Share this post


Link to post
Share on other sites
Make some boolean flags, set the flag to true onKeyPress and set the flag to false onKeyRelease. Then, if you don't want to listen to any keypresses while moving, simply check the flag.

Share this post


Link to post
Share on other sites
hi,that's was my first choice, but it still listening, so if i press twice it moves twice, well in the function i have some loops...

thanks,

Share this post


Link to post
Share on other sites
Quote:
Original post by detryo
hi,that's was my first choice, but it still listening, so if i press twice it moves twice, well in the function i have some loops...

thanks,


The listeners are always going to listen for events, but as Shakedown suggested, using boolean flags ensures the event are not going to have any effects.

Share this post


Link to post
Share on other sites
If I understand correctly, you don't want the key to repeat while pressed. You need to define a second boolean to set once you have read the keypress flag.

boolean keys[] = new boolean[1];
boolean arrowPressed = false;

public void checkKeys() {
if(keys[0] && !arrowPressed) {
//do action
arrowPressed = true;
}
if(!keys[0]) {
arrowPressed = false;
}
}

public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == /*arrow key code */) {
key[0] = true;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == /*arrow key code */) {
key[0] = false;
}
}



This will only read 1 key press, even if the key is held down.

Share this post


Link to post
Share on other sites

This topic is 3483 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this