I want do develop a little game in java and swt. For this reason, I have to react to KeyEvents. How can I check if e.g. the up arrow key and 'q' are pressed together?
Thanks in advance
phineas
I want do develop a little game in java and swt. For this reason, I have to react to KeyEvents. How can I check if e.g. the up arrow key and 'q' are pressed together?
Thanks in advance
phineas
SWT does not have a concept of pressed together (unless you are talking about standard modifier keys such as shift, alt, etc). What you can do is catch both the up arrow and 'q' key events separately. If timing is an issue then you can compare the two time stamps (There is a time field in KeyEvent) and determine what your definition of together is (50 ms? you may want to experiment).
If q is being used like a modifier then this is easier because you can set a flag when q is pressed and when the up arrow is pushed you can check whether the q flag is set. This would be much easier than worrying about timing. Of course don't forget to clear the q flag when the key is released.
rancidfishbreath's solution will work. For an excellent example, see http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet25.java
Thanks for your answers! I just thought I could develop a little pong game quite fast, but I didn't kow key bindings are so difficult to handle! The main obstacle is that the two paddles must be moved in an independent way (currently the pressing keys interfere the opponents moves and vice versa).
Actually, you can implement that. Each key down and key up has it's own event fired, so you know exactly what keys are being pressed when and what keys are down at any moment.
Example: When the down arrow's key down event is fired, you start moving the right paddle down. When the X key's key down event is fired you start moving the left paddle down. When the X key's key up event is fired, you stop moving the left paddle, and when the down arrow's key up event is fired, you stop moving the right paddle. => You control them independently of each other.
You can wrap all that in some sort of utility that will make the solution cleaner.