簡體   English   中英

綁定兩個JSpinners增量和減量

[英]binding two JSpinners increment and decrement

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM