Java/Swing: Problem with key listener

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-05-19T03:36:35Z Indexed on 2010/05/19 3:40 UTC
Read the original article Hit count: 209

Filed under:
|
|

I have a search dialog with a JTextField that's being used as a search box.

When the user types something, it searches the DB, shows the result in a JTable and selects the first item in it.

If the first result is what they were looking for, I want to let them quickly accept the dialog, by pressing Enter (while the JTextField is focused).

So I added a KeyListener to the JTextField and it's working OK.

Now the problem: The user opens can open the dialog by pressing Enter when a "Search" button on the dialog's parent frame is focused.

The dialog is displayed and the JTextField gets the keyReleased event (from the Enter key that displayed it), so it shows up and closes. If the user holds Enter down, then the JTextField receives the keyPressed, keyTyped and keyReleased events.

How can I fix without resorting to ugly workarounds?

Platform is Windows 7 x64, btw.

Test NetBeans project here: http://dl.dropbox.com/u/6354360/KeyListenerTest.zip

Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about swing