开发者

Java/Swing: Problem with key listener

开发者 https://www.devze.com 2022-12-31 07:41 出处:网络
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.

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 th开发者_高级运维e 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.

Thanks.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消