A KeyListener problem

I am in the final testing phase of my assignment and i discovered some strange behavior.

My application has 2 search fields where user can enter the desired search criteria and if user hit <enter> in a search field, the search is executed. So that's working fine, not hard to implement and makes the GUI more user-friendly. Code fragment to do this:

if the specified criteria result in no records, i show a message to the user (using JOptionPane.showMessageDialog). So the modal dialog popups, with only an ok-button (that has the focus) user hit <enter> (to close the dialog), the dialog closes but search is executed again (resulting in the same dialog showing) and so it's kind of a infinite loop if you use the mouse or escape key for example, the dialog just disappears.

i was not expecting this side effects from something that seemed so easy. anybody any idea what's the problem here or what i'm doing wrong?

I first searched the SCJD-forum, nothing relevant found, so decided to post my question. But afterwards i tried a search on all forums and i found this thread.

And it's about jdk 1.4, but it still stands for jdk 6: if i change my code in the 1st post and replace keyReleased by keyPressed it works perfectly, so i'm delighted to find a solution this quick, but also a little bit about the reason why it's only seems to work with keyPressed

Hi Roel, when there is no search results, the RecordNotFoundException should catch it and once in the catch block, the code should stop. So it's kinda weird you had infinite loop problem.

The text field key listener should be keyPressed. If you used keyReleased which you did earlier, the actual search won't happen until the enter key is released. IMO using the enter key to execute an action instead of just using those mnemonics (Alt+key) is a bit of a hassle because there will seem to be more coding hence more difficult to maintain - unless you use a JOptionPane which the OK button is already enter-key enabled.

if you close the dialog with the mouse or with <esc> button, then there is no problem

K. Tsang wrote:IMO using the enter key to execute an action instead of just using those mnemonics (Alt+key) is a bit of a hassle because there will seem to be more coding hence more difficult to maintain

It takes only 4-5 extra lines to enable <enter> to start the search and i find it much more easy and simpler using <enter> than using the mnemonic. i provided both, so user can use possibility he/she likes the most

But still wondering why there is a difference between keyPressed and keyReleased methods in the KeyListener (used in combination with a Dialog, as also described in the thread i mentioned in my first post).