0

i have created two JSpinners with netbeans Form, i want to link the two JSpinners so that if the value of one of them decrements, the value of the other incrementes and vice versa. i tried with this piece of code but it's not working :

 int currentValue = durexep_spin.getValue();
private void durexep_spinPropertyChange(java.beans.PropertyChangeEvent evt) {                                            


  int p = soldexep_spin.getValue();
  int q = durexep_spin.getValue();
  if(q<currentValue){
    soldexep_spin.setValue(p+1);  
  }
  else if (q>currentValue){
      soldexep_spin.setValue(p-1);
  }
Sam
  • 17
  • 6

1 Answers1

1

You could create a subclass of javax.swing.event.ChangeListener with two references in its constructor: JSPinner base and JSpinner image. Then code the stateChanged method to update the value of the image, from the current value of the base (assuming you know what the sum of both values make).

Last, you only have to instantiate two instances of the listener and attach one to each JSpinner.

{
    // ... Initialization of the JPanel ...
    int constantSum=10;
    soldexep_spin.addChangeListener(new MyListener(soldexep_spin, durexep_spin, constantSum));
    durexep_spin.addChangeListener(new MyListener(durexep_spin, soldexep_spin, constantSum));
}

private class MyListener implements javax.swing.event.ChangeListener
{
    private final JSpinner base;

    private final JSpinner image;

    private final int constantSum;

    public MyListener(JSpinner base, JSpinner image, int constantSum)
    {
        super();
        this.base=base;
        this.image=image;
        this.constantSum=constantSum;
        // Initializes the image value in a coherent state:
        updateImage();
    }

    public void stateChanged(ChangeEvent e)
    {
        updateImage();
    }

    private void updateImage()
    {
        int baseValue=((Number)this.base.getValue()).intValue();
        int imageValue=((Number)this.image.getValue()).intValue();
        int newImageValue=this.constantSum - baseValue;
        if (imageValue != newImageValue)
        {
            // Avoid an infinite loop of changes if the image value was already correct.
            this.image.setValue(newImageValue);
        }
    }
Little Santi
  • 8,563
  • 2
  • 18
  • 46