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
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.
3 Comments
JApplet. Swing is more advanced than AWT, and AWT is so old most people have forgotten the details. Also, use key bindings.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