当前位置: 代码迷 >> java >> 绑定两个JSpinners增量和减量
  详细解决方案

绑定两个JSpinners增量和减量

热度:41   发布时间:2023-07-25 19:17:03.0

我用netbeans Form创建了两个JSpinners,我想链接这两个JSpinners,以便如果其中一个的值递减,则另一个的值递增,反之亦然。 我尝试了这段代码,但是没有用:

 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);
  }

您可以创建javax.swing.event.ChangeListener的子类,在其构造函数中具有两个引用:JSPinner base和JSpinner image。 然后,对stateChanged方法进行编码,以从基数的当前值更新图像的值(假设您知道两个值的总和是多少)。

最后,您只需实例化侦听器的两个实例,并将一个实例附加到每个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);
        }
    }
  相关解决方案