aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes simple question about swing? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "simple question about swing?" Watch "simple question about swing?" New topic
Author

simple question about swing?

Bilal Ali
Ranch Hand

Joined: Jun 14, 2007
Posts: 66
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

Joined: Mar 05, 2002
Posts: 229
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

Joined: Sep 20, 2005
Posts: 862
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)


bitguru blog
Manuel Moons
Ranch Hand

Joined: Mar 05, 2002
Posts: 229
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: simple question about swing?