慎用property绑定
原因:
1.常会出现意料之外的情况
2.代码可读性降低
举例:
Circle circle = new Circle(100,100,50);
circle.getStyleClass().add("test-circle");
…………(这后面就是circle对应的逻辑代码)
circle.centerXProperty().bind(circle.strokeWidthProperty().divide(2));
//以上就是源文件中的代码
//stage.java
scene.getStylesheets().add("test/test.css");
//css文件:test.css
.test-circle{
-fx-fill:white;
-fx-stroke:black;
-fx-stroke-width:1;
}
//以上是常规情况下circle的样式
.test-circle:hover{
-fx-fill:blue;
-fx-stroke:red;
-fx-stroke-width:10;
}
这样倒是可以使centerX根据css中的设定动态地变化,但倘若涉及更多的数据操作,这样做会导致代码复杂性增大,因为property要不断的绑定,使得原本的数据变得运算看起来更加繁重
//原本想让centerX依次从(0,0),(1,0)逐步变到(0,5050)
int i = 0;
for(int j = 0;j <= 100;j++){
i += j;
circle.setCenterX(i);
}
但是换成property绑定就变成了
IntegerProperty i = new SimpleIntegerProperty(0);
circle.centerXProperty.bind(i);
for(int j = 0;j <= 100;j++){
i = i.add(i);
}
这只是一个数据绑定,倘若多数据在一起各种绑定,你需要彻底读懂整个代码加上计算才能知道circle.centerX具体怎么变化,而在需要改变的地方显式加上 circle.setCenterX(i);会大大增强可读性