1. 程式人生 > >【javaFX】屬性繫結

【javaFX】屬性繫結

         在引入屬性繫結之前,先來看個簡單的例子:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
public class ShowCircle extends Application{
	@Override
	public void start(Stage stage) {
		Circle circle=new Circle(100,100,50);
		Pane pane=new Pane();
		pane.getChildren().add(circle);
		Scene scene=new Scene(pane,200,200);
		stage.setTitle("ShowCircle");
		stage.setScene(scene);
		stage.show();
	}
	public static void main(String[] args) {
		Application.launch(args);
	}
}

      該程式在視窗正中間顯示一個圓,但是當手動拉伸視窗之後,圓的位置並沒有變化。還是位於相對座標(100,100)的位置。實際應用時,我們經常想要一個圖形正好顯示在視窗的正中間,不論視窗大小怎麼。那麼,這種功能就需要用到屬性繫結。

   簡單講,屬性繫結就是將某個屬性值(目標物件)和另一個數值(源物件)進行關聯,讓二者存在某關係,當觀察源發生改變時,為保證二者關係不變,目標物件也相應改變。例如,上例中,可令圓心橫縱座標分別繫結為窗體寬和高的1/2,實現圓一直在窗體正中間。如下:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
public class ShowCircle extends Application{
	@Override
	public void start(Stage stage) {
		Circle circle=new Circle(50);
		Pane pane=new Pane();
		pane.getChildren().add(circle);
		Scene scene=new Scene(pane,200,200);
        //以下兩行實現了屬性繫結
		circle.centerXProperty().bind(pane.widthProperty().divide(2));
		circle.centerYProperty().bind(pane.heightProperty().divide(2));
		stage.setTitle("ShowCircle");
		stage.setScene(scene);
		stage.show();
	}
	public static void main(String[] args) {
		Application.launch(args);
	}
}

現在對這兩行進行深入的分析:

    circle.centerXProperty().bind(pane.widthProperty().divide(2));
    circle.centerYProperty().bind(pane.heightProperty().divide(2));

1.繫結屬性和繫結源都是物件,屬於javafx.beans.property.Property類,而且繫結源必須實現javafx.beans.value.ObervableValue介面。

2.javaFX為基本資料型別和字串型別建立了相應的繫結屬性。分別為:DoubleProperty, FloatProperty, LongProperty, IntegerProperty,BooleanProperty,StringProperty,即為各種型別包裝類名後加Property。同時它們都實現了ObervableValue介面,也可以作為繫結源。

3.Property物件的add, subtract, multiply, divide方法對物件包裝的值進行運算,返回與之同類的包裝了運算結果的Property物件。

將上面的第一行拆分可得到:

    DoubleProperty centerX=circle.centerXProperty();
    DoubleProperty width=pane.widthProperty();
    DoubleProperty halfOfWidth=width.divide(2);
    centerX.bind(halfOfWidth);

 另外,可以使用bindBidirectional方法使兩個實現了ObervableValue介面的屬性物件雙向繫結,改變任何一個值都會引起另一個的相應變化。