Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 349
David Avatar asked May 27 '11 14:05

David


1 Answers

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

like image 72
Waldheinz Avatar answered Sep 28 '22 06:09

Waldheinz