views:

198

answers:

1

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.

+2  A: 

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

You should NOT be using a KeyListener for this. You should be adding a an ActionListener to the textfield.

In general you should not use KeyListeners you should be using Key Bindings.

camickr
Thanks, that worked. I'm new to Java, I didn't know about key bindings. I forgot to mention I had tried setting an accelerator from NetBeans' action dialog, but it wasn't working, so I tried the key listener. Thanks again!
Mike