Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple question about swing?

 
Bilal Ali
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Respected Members,
I am making a very simple program in Java swing using jdk1.4.2, the program simply contains a JFrame and nothing else,what it is simply doing that I have binded an event to this frame and which is that every time the user presses Ctrl-F3(control and F3 key) so a message is displayed stating for example that "you pressed right key", but my program is not working, the probelm is that the event dont get fired,if I test it indivisually for Ctrl or F3 than the event is fiered and every thing works fine, teh code is:

 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every time a key is pressed a key pressed event is thrown. This means that you will actually receive an event for the F3 key AND another event for the Ctrl key.

What you want to do is remember that you pressed the "Ctrl" key and remember that you pressed the "F3" key. And test on that when the other key is pressed. When the key released event comes you must remove the pressed keys from your memory.

I don't know if this is clear enough for you. I will give a short example:

Step 1: Key pressed Event for the Ctrl key
--> you store the key (or set a boolean or ...)
Step 2: Key pressed Event for the F3 key
--> you check the previously pressed key (check the boolean or ...)
Step 3: Key released Event for the Ctrl key
--> now you switch back your boolean (the key is no longer pressed)

Hope this helps!
 
Brian Cole
Author
Ranch Hand
Posts: 908
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bilal Ali:
if (iCode == KeyEvent.VK_CONTROL && iCode == KeyEvent.VK_F3)


You can't really expect iCode to be equal to two different int values simultaneously, can you? Instead try something like

if (evt.getKeyCode() == KeyEvent.VK_F3 && (evt.getModifiers() | KeyEvent.CTRL_MASK) != 0)
 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes, Brian is right!

I forgot about that! The control key is a special key that can be checked using the "getModifiers" call!

My solution can also be used when you want to see if multiple keys are pressed simultanuously but when using the modifier keys (alt, ctrl, shift) it is not the most elegant solution.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic