David
David

Reputation: 16038

Detect all changes (made by the user) to the text in controls on the form

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

Answers (2)

Waldheinz
Waldheinz

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

aioobe
aioobe

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

Related Questions