JavaFX可通过Property监听,做出自己的操作,在图形的Property监听中应用较多。
// Double监听
方式一(可知详细变化):
DoubleProperty doubleProperty = new SimpleDoubleProperty(初始化的double值);
doubleProperty.addListener(this::doublePropertyChange);
private void doublePropertyChange(ObservableValue<? extends Number> observable, Number oldValue, Number newValue){
double value = (double)newValue;
}
// 坑 最小值变化不触发改变的监听事件
doubleProperty.set(doubleProperty.get() + Double.MIN_VALUE);
方式二(可知详细变化):
doubleProperty.addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
//操作
}
});
可简化为
doubleProperty.addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
double value = (double)newValue;
});
方式三(可知变化了):
ReadOnlyDoubleWrapper doubleProperty = new ReadOnlyDoubleWrapper(初始化的double值);
doubleProperty.getReadOnlyProperty().addListener(o -> doSomething());
private void doSomething(){
}
图形的属性可绑定一个Property,在Property变化时,属性也跟着变化,可广泛应用于动画。
Button myButton = new Button();
myButton.setText("Test");
SimpleDoubleProperty simpleDoubleProperty = new SimpleDoubleProperty(100);
myButton.translateXProperty().bind(simpleDoubleProperty);
simpleDoubleProperty.set(0);
// 想通过setTranslateX方式改变translateX属性,必须解绑
myButton.unbind();
myButton.setTranslateX(50);
Property可以进行计算,元素的改动会同步到计算结果中,同时字符串也可以和数值联合:
SimpleDoubleProperty simpleDoubleProperty = new SimpleDoubleProperty(10);
SimpleDoubleProperty simpleDoubleProperty1 = new SimpleDoubleProperty(10);
SimpleDoubleProperty simpleDoubleProperty2 = new SimpleDoubleProperty(10);
DoubleBinding doubleBinding = simpleDoubleProperty2.add(simpleDoubleProperty).add(simpleDoubleProperty1);
System.out.println(doubleBinding.getValue());
simpleDoubleProperty2.set(0);
System.out.println(doubleBinding.getValue());
System.out.println(new SimpleStringProperty("P:").concat(doubleBinding.asString()).getValue());