Mike W
Mike W

Reputation: 1148

capturing input from JTextInput when user doesn't press Enter

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?

Upvotes: 0

Views: 838

Answers (3)

icon666
icon666

Reputation: 33

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...

Upvotes: 0

Chuk Lee
Chuk Lee

Reputation: 3608

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

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

For document changes use changeUpdate()

Upvotes: 1

SimonC
SimonC

Reputation: 6718

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.

Upvotes: 1

Related Questions