我試圖使用某些綁定功能在JavaFX中進行自定義控件。這是我的問題:我有一個DoubleProperty
類,我用它來計算我的自定義控件中元素的位置。下面是代碼:未綁定調用JavaFX Property的invalidate()方法
public class CustomControl extends Region {
private DoubleProperty positionProperty;
public CustomControl() {
positionProperty= new DoublePropertyBase(0.0) {
@Override public Object getBean() { return CustomControl.this; }
@Override public String getName() { return "position"; }
@Override protected void invalidated() { updatePostion(); }
};
}
public DoubleProperty positionProperty() { return positionProperty; }
public double getPosition() { return positionProperty.get(); }
public void setPosition(double value) { positionProperty.set(value); }
private void updatePosition() {
double value = doubleProperty.get();
//compute the new position using value
}
}
在我的應用我有兩個CustomControl
S和我想,當我呼籲他們的第一個方法setPosition()
,第二個更新其部件的位置爲好。要做到這一點我綁定兩個CustomControl
S的像這樣的positionProperty
:
CustomControl control1 = new CustomControl();
CustomControl control2 = new CustomControl();
control2.positionProperty.bind(control1.positionProperty);
後來,當我打電話例如
control1.setPosition(50.0);
只有control1
部件的位置被更新,確實是我的呼喚實際上調用setPosition()
的方法positionProperty
的invalidated()
的control1
的實際名稱,但不是我所預期的positionProperty
的contol2
中的一個。我如何實現我想要的?謝謝!
PS:我也注意到,使用方法bindBidirectional()
而不是bind()
作品,但不應該它的工作只用bind()
嗎?
編輯:示例代碼,請訪問:https://[email protected]/luca_bertolini/customcontrolexample.git
你正在創建'DoubleProperty'的匿名類實現的任何原因?你的問題可能源於你重寫'invalidated'方法,而不調用基('super')方法。 – Itai
@sillyfly我創建了一個匿名類,因爲我需要在屏幕上擁有大量的這些「CustomControl」,並且使用匿名類而不是在屬性上設置偵聽器將提供更少的內存使用量和更少的計算複雜性。另外'invalidate()'的默認實現是空的,所以如果我調用'super.invalidate()',它不會有太大的改變。 –
發佈[MCVE]。我測試了它,它完全按照預期工作('System.out.println(control2.getPosition());'顯示'50.0')。在你沒有發佈的代碼中,其他地方一定有錯誤。 –