I have a few different input textboxes which you can enter a command into, press enter, and then it pulls up some information. I have a few different textboxes who (applying to different parts of information). When I press enter, it also moves the focus onto the next input box. How do I stop this? I can't simply use the consume() method in the keyevent class since that would entirely block the enter key, which is not what I want
-
Why don't you use `keyevent.consume()` on `keyvent.getKeyCode() == KeyEvent.VK_ENTER`, and also call the method which pulls the information from within your `KeyListener`? Or is the `Enter` key doing anything fancier than pulling and displaying the information? – Anthony Accioly Apr 03 '12 at 17:13
-
1Had you tried [requestFocusInWindow(...)](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocusInWindow()) ? – nIcE cOw Apr 03 '12 at 17:15
-
http://stackoverflow.com/questions/1068853/stopping-default-behavior-of-events-in-swing is a interesting read. akf accepted answer implements my suggestion, camickr key binding solution is also very good. – Anthony Accioly Apr 03 '12 at 17:26
-
@AnthonyAccioly I am modifying someone elses application, so I'm not so clear on that yet. I will take a look at you suggestions later – user1015214 Apr 03 '12 at 17:44
2 Answers
InputVerifier
, described in Validating Input, is designed for exactly this purpose:
A component's input verifier is consulted whenever the component is about to lose the focus. If the component's value is not acceptable, the input verifier can take appropriate action, such as refusing to yield the focus on the component…
Addendum: As suggested in the article Text Validation, InputVerifier
should be an integral part of validation, designed so that the user knows immediately why something is awry.

- 203,806
- 29
- 246
- 1,045
-
Very good answer as always ;). Now lets wait for camickr hehehe. – Anthony Accioly Apr 04 '12 at 01:57
-
1*"Now lets wait for camickr.."* [Last seen](http://stackoverflow.com/users/131872/camickr) on Feb. 21st. – Andrew Thompson Apr 04 '12 at 04:40
-
@Andrew, camickr and trashgod have a tendency to show up together at posts I've written / commented on, It was a joke. But let me stop polluting stackoverflow hehehe. – Anthony Accioly Apr 04 '12 at 19:59
Actually, I just found out how to fix this issue. I used the method belonging to Container called requestFocus() (see http://www.javaworld.com/javaworld/jw-07-1998/jw-07-swing-focus.html). In each element I added this line to the end of the keyEvent action and it worked perfectly!

- 2,733
- 10
- 36
- 66
-
See also [*How to Write a Key Listener*](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html), which makes a similar suggestion. – trashgod Apr 04 '12 at 21:39