JavaFX學習筆記——重要理念的建立與辨析(六)
慎用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);會大大增強可讀性