0

I have a class with two JSpinner objects in them, x and y. I have one change Listener which is added to both. can someone tell me how I can implement my change listener so that the listener can tell the difference between the two objects. e.g. Pseudocode:

if(source equals x)
    do this
else if(source equals y)
    do that

Thanks guys,

andrew Patterson
  • 559
  • 2
  • 6
  • 19

2 Answers2

3

You can simply use an anonymous class to implement the listener for each spinner

For example if you want to implement change listener to x, you can do something like:

x.addChangeListener(new ChangeListener()
{
   public void stateChanged(ChangeEvent e)
   {
   }
});

and same thing for y

Kakalokia
  • 3,191
  • 3
  • 24
  • 42
2

It's more prudent (as Ali has pointed out, +1) to use a single listener per control where possible. It isolates the event/action and makes it generally easier to read and make sense of...

If you can't see yourself using this, then every EventObject has a getSource method which is a reference to the control which raised the event...

public void stateChanged(ChangeEvent e)
{
    if (e.getSource() == xControl) {
        // xControl updated
    } else if (e.getSource() == yControl) {
        // yControl updated
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366