I really do not want to listen to DocumentListener. It generates too many events for me. I am interested in listening only when the focus moves away from this specific JtextField. Adding ActionListener will generate an event only when return key is pressed. I would like to get it when the user moves away with a tab key or by moving the mouse away. Is this possible? Thanks and Regards
Asked
Active
Viewed 306 times
0
-
1Sounds like you are after some validation mechanism. Consider using a `JFormattedTextField` in that case (see [this example](http://stackoverflow.com/a/13424140/1076463)) – Robin Dec 13 '12 at 16:39
-
+1 agreed with Robin. Seems like you want to validate the data in `JTextField`, which should rather be done using `JFormattedTextField`. See this example: http://stackoverflow.com/questions/11881301/best-way-to-constrain-user-to-enter-a-time-in-a-jtextfield/11881523#11881523 – David Kroukamp Dec 13 '12 at 18:04
-
Alternatively have a look at `InputVerifier`: http://docs.oracle.com/javase/7/docs/api/javax/swing/InputVerifier.html – David Kroukamp Dec 13 '12 at 18:11
1 Answers
1
Use FocusListener. focusLost will help you when user moves to some other fields.
JTextField jf = new JTextField();
jf.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
// here you can have your code when user moves out
}
@Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
}
} );

Vinay
- 6,891
- 4
- 32
- 50
-
1Rather use `FocusAdapter`as it allows the overriding of a single method. – David Kroukamp Dec 13 '12 at 18:06
-
All solutions look good to me. However for my immediate need focus lost event suffuses. Thanks all – Manu Dec 14 '12 at 01:20
-
@David. Yeah FocusAdapter would be good if there was need for only foculs lost event.Thanks for that.. – Vinay Dec 14 '12 at 03:31