2

I am creating a game in java applets. The game responds on keypressed event by implementing keylistener iterface in my class. I want that until previous keypressed event is completed, no new events can be raised by keyboard. How is this possible? Thanks

2 Answers 2

5

Yes it's possible. You can either remove the listener and re-add it, or have a boolean class field control the behavior of the KeyListener code. Incidentally, if this is a Swing project and you're creating a JApplet, you should be using Key Bindings not KeyListeners. The Key Bindings Tutorial will tell you why.

Sign up to request clarification or add additional context in comments.

3 Comments

@Hovercraft : The game I am creating is tetris using Applet not JApplet. Is this the correct way to do it, beacuse its not working after first event is raised? public void keyPressed(KeyEvent e){ removeKeyListener(this); //handle the vent addKeyListener(this); }
"Is this the correct way to do it," You started to go wrong at 'Applet'. I agree with the Hovercraft and mKorbel. Use a JApplet. Swing is more advanced than AWT, and AWT is so old most people have forgotten the details. Also, use key bindings.
@AndrewThompson: well I think I am on wrong track. lets see if there is a way to convert Applet code into JApplet. Its going to be a long way back.
0

the events from the keyboard will occur regardless your code in listeners, user presses the key and event is fired by OS and then it comes to java. Now, its up to you to decide whether you want to listen to this event or not. The event handling in Java is done by listeners. When you call addXXXListener, - the listener "got registered" in java and it will be notified for events, you call removeXXXListener - and the listener gets "deregistered". This is how it works. In the listener code you decide what to do with events it gets from java.

Having said that, the answer to your question in general is: you can ignore events in your listener whenever you need (when you got the "previous keypressed") Another approach would be calling removeListener/addListener when needed.

Yet another thing, Swing is Single Threaded, so its not possible that there will be two events occuring "concurrently", so the "next key event" will be fired only after "the previous event is completed"... Of course you can write your code inside the listener so that it would spawn threads by itself, but its an entirely different story.

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.