我创建了两个带有netbeans Form的JSpinner,我想链接两个JSpinner,这样如果其中一个的值减少,则其他增量的值减去,反之亦然。我尝试使用这段代码,但它不起作用:
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);
}
答案 0 :(得分: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);
}
}