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 ActionListene开发者_运维技巧r'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?
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.
muJTextField.addFocusListener(/* focus listener here */);
for focus changes
myJTextField.getDocument().addDocumentListener(/* document listener here */);
for document changes
For document changes use changeUpdate()
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...
精彩评论