views:

104

answers:

2

I've got a JTextField, and I'd like the system to do some processing on what the user typed whenever the user leaves the text field. The ActionListener that you can add to just the JTextField only fires when the user presses enter, however.

I'd like the processing routine to run whenever the user leaves the text box by any means - tabs, clicks out of it, presses enter, etc. (The processing in question is to save the text the user typed to the appropriate data object, nothing fancy.)

My google-fu has failed on this one: I'm confident that it's possible, I just can't see how.

+6  A: 

Add a FocusListener.

It's worth noting that this is a relatively low-level listener. On JComboBox it wont work unless you find the text field (and perhaps button) that the particular PL&F inserts. Swing is a bit odd that way (amongst many other ways).

Although for my money, non-cosmetic changes that happen when focus leaves a field give poor user experience. Much better to do any relevant changes on every change with a listener on the text field's document.

Tom Hawtin - tackline
Aha! FocusListener is what I was vaguely remembering. The action in question is to save the text the user typed - is that better to do via a listener on the document, do you think?
Electrons_Ahoy
Yes, but sensibly. You probably want to make sure that you aren't saving the entire document every keystroke. Small rest period between saves (and don't overlap). If the document is large (unlikely with a `JTextField`) then just append to a log most of the time. Having said that, moving fields may be a good time to be a bit more urgent about saving.
Tom Hawtin - tackline
For the record, the focus listener did exactly what I need it to do. Thanks!
Electrons_Ahoy
A: 

If you want to edit the text as it is typed then you should use an DocumentFilter.

If you want to validate the text as a complete entity then you can use an InputVerifier.

camickr