views:

33

answers:

3

In my Swing app, I have a screen that has a bunch of JTextFields. Each JTextField uses an ActionListener's actionPerformed method to copy the user-entered text to my data model object.

This method seems to only be called if the user presses Enter. How can I copy the user-entered text to my data model object if the user doesn't press Enter but instead 1) tabs between fields or 2) uses the mouse to click from one field to the next?

+1  A: 

muJTextField.addFocusListener(/* focus listener here */); for focus changes

myJTextField.getDocument().addDocumentListener(/* document listener here */); for document changes

For document changes use changeUpdate()

Chuk Lee
+1  A: 

If you only want to perform an action when the user moves away from the field (not on every character changing in the field) then listen to the focus events:

JTextField textField = ...
textField.addFocusListener(new FocusAdapter(){ void focusLost(FocusEvent e) 
  { doSomething(); } );

You might want to take a look at JFormattedTextField which handles this kind of thing for you.

SimonC
A: 

the problem with mouseclick, is that the component you click on must grab focus, else focus lost will not be called... i had the same problem, so i used a timer to commit my code, every x milliseconds...if you sure that focus lost will be called when you click on some other component, a simple focus listener will do the trick...

icon666
If the component you're clicking on doesn't grab focus then something is going wrong...
SimonC