Reputation: 16038
I have a program with a Save() method that saves all data in spinners and textfields on the form. Is there a way to call "Save()" every time the user makes a change to a textfield or spinner? Something similar to a generic event handler.
Thanks
Upvotes: 5
Views: 443
Reputation: 10487
You can hook up a single instance of ChangeListener to all your controls, which could look like (when an inner class):
private class ListenerImpl implements ChangeListener {
public void stateChanged(ChangeEvent e) { save(); }
}
to add this listener in one go you can loop over the children of your Container
like this:
final ListenerImpl l = new ListenerImpl();
for (Component c : getComponents()) {
if (c instanceof JSpinner) {
((JSpinner)c).addChangeListener(l);
} else if (c instanceof JTextPane ) { } // ... other types of components
}
you have to look for the different types of components because there is no interface which defines the addChangeListener(..)
method (that I am aware of).
Upvotes: 3
Reputation: 421020
I would suggest that you add a ChangeListener
or a FocusListener
to each of the controls in the form and call Save()
in one of the call-back methods. (Actually, I would probably go for the FocusListener
and call Save()
from the focusLost
-method.)
Upvotes: 2