Java fx 中的 binding探索

Binding在fx的使用


Binding的概念

soldPrice = listPrice - discounts + taxes
通過這個表達式,如果你知道listPrice, discounts, taxes, 你是不是很快能計算出soldPrice? 這就是一個binding的關系,反之如果你知道了一個soldPrice,你能推算出其他3項嗎?答案是no. 這里為我們揭示了binding中存在方向的概念,是單向 or 雙向。


NumberBinding

  1. 利用property對象返回一個NumberBinding對象,當它的值沒有被計算出來,它是invalid:
//NumberBinding
IntegerProperty digit1 = new SimpleIntegerProperty(1);
IntegerProperty digit2 = new SimpleIntegerProperty(2);
NumberBinding numberBinding = digit1.add(digit2);
System.out.println("sum.isValid(): " + sum.isValid());
System.out.println(sum.getValue());
System.out.println("sum.isValid(): " + sum.isValid());
Paste_Image.png

2.或者它依賴的propery更新的時候,它也會失效

digit1.set(3);
System.out.println("sum.isValid(): " + sum.isValid());
Paste_Image.png

Binding in String

  1. 直接使用property
//StringBinding
StringProperty str1 = new SimpleStringProperty("11");
StringProperty str2 = new SimpleStringProperty("22");
StringProperty str3 = new SimpleStringProperty("33");
str3.bind(str1.concat(str2));
System.out.println(str3.get()); 

2.使用StringExpression

StringProperty str1 = new SimpleStringProperty("11");
StringProperty str2 = new SimpleStringProperty("22");
StringExpression desc = str1.concat(str2);
System.out.println(desc .get());    

3.使用String binding

StringProperty str1 = new SimpleStringProperty("11");
StringProperty str2 = new SimpleStringProperty("22");
StringBinding strBinding = new StringBinding() {
                  {
                  bind(str1.concat(str2));
              }
            @Override
            protected String computeValue() {
                return str1.concat(str2).get();
            }};
System.out.println("StringBinding: + " + strBinding.getValue());
str2.set("22");
System.out.println("StringBinding: + " + strBinding.getValue());

Binding of boolean

通過property之間的邏輯方法比較構造。

Book b1 = new Book("J1", 90, "1234567890");
Book b2 = new Book("J2", 80, "0123456789");
ObjectProperty<Book> book1 = new SimpleObjectProperty<>(b1);
ObjectProperty<Book> book2 = new SimpleObjectProperty<>(b2);
// Create a binding that computes if book1 and book2 are equal
BooleanBinding isEqual = book1.isEqualTo(book2);
System.out.println(isEqual.get());// false
book2.set(b1);
System.out.println(isEqual.get());// true
IntegerProperty x = new SimpleIntegerProperty(1);
IntegerProperty y = new SimpleIntegerProperty(2);
IntegerProperty z = new SimpleIntegerProperty(3);
// Create a boolean expression for x > y && y <> z
BooleanExpression condition = x.greaterThan(y).and(y.isNotEqualTo(z));
System.out.println(condition.get());// false
// Make the condition true by setting x to 3
x.set(3);
System.out.println(condition.get());// true

單向綁定以及雙向綁定

單向綁定實例 (C = A X B)

單向綁定只受綁定對象的影響,Binding對象(或這屬性)自身的變化不影響綁定對象。

public class BoundProperty {
    public static void main(String[] args) {
        IntegerProperty x = new SimpleIntegerProperty(10);
        IntegerProperty y = new SimpleIntegerProperty(20);
        IntegerProperty z = new SimpleIntegerProperty(60);
        z.bind(x.add(y));
        System.out.println("After binding z: Bound = " + z.isBound() + ", z = "
                + z.get());
        // Change x and y
        x.set(15);
        y.set(19);
        System.out.println("After changing x and y: Bound = " + z.isBound()
                + ", z = " + z.get());
        // Unbind z
        z.unbind();
        // Will not affect the value of z as it is not bound to x and y anymore
        x.set(100);
        y.set(200);
        System.out.println("After unbinding z: Bound = " + z.isBound()
                + ", z = " + z.get());
    }
}
Paste_Image.png

雙向綁定

雙向綁定,改變任何一方,都會觸發另一方的改變,給予這種前提(X=Y), 兩邊必須是同一類型。

一個簡單的例子:

public class BidirectionalBinding {
    public static void main(String[] args) {
        IntegerProperty x = new SimpleIntegerProperty(1);
        IntegerProperty y = new SimpleIntegerProperty(2);
        IntegerProperty z = new SimpleIntegerProperty(3);

        System.out.println("Before binding:");
        System.out.println("x=" + x.get() + ", y=" + y.get() + ", z=" + z.get());

        x.bindBidirectional(y);
        System.out.println("After binding-1:");
        System.out.println("x=" + x.get() + ", y=" + y.get() + ", z=" + z.get());

        x.bindBidirectional(z);
        System.out.println("After binding-2:");
        System.out.println("x=" + x.get() + ", y=" + y.get() + ", z=" + z.get());

        System.out.println("After changing z:");
        z.set(19);
        System.out.println("x=" + x.get() + ", y=" + y.get() + ", z=" + z.get());

        // Remove bindings
        x.unbindBidirectional(y);
        x.unbindBidirectional(z);
        System.out.println("After unbinding and changing them separately:");
        x.set(100);
        y.set(200);
        z.set(300);
        System.out.println("x=" + x.get() + ", y=" + y.get() + ", z=" + z.get());
    }
}
Paste_Image.png

流式API

流式 API 是Java fx 在Binding提供的福利 API. 通過這些API,可以向DSL 一樣描述 依賴關系。

public class FluentAPITest {

    public static void main(String[] args) {
        
        //String property
        StringProperty s1 = new SimpleStringProperty("XX");
        StringProperty s2 = new SimpleStringProperty("qq");
        StringExpression s3 = s1.concat(s2);
        System.out.println(s3.get());
        
        //Number property
        IntegerProperty i1 = new SimpleIntegerProperty(4);
        IntegerProperty i2 = new SimpleIntegerProperty(2);
        IntegerProperty i3 = new SimpleIntegerProperty(2);
        IntegerBinding ib = (IntegerBinding) i1.add(i2).subtract(i2).multiply(i2).divide(i3);
        System.out.println(ib.get());
        
        //Boolean Property
        BooleanProperty b1 = new SimpleBooleanProperty(false);
        BooleanProperty b2 = new SimpleBooleanProperty(true);
        BooleanBinding b3 = b1.isEqualTo(b2).isNotEqualTo(b2).not().not();
        System.out.println(b3.get());
    }
}
Paste_Image.png

三元 API 操作

new When(condition).then(value1).otherwise(value2)
condition對象必須實現了ObservableBooleanValue接口

public class TernaryTest {
    public static void main(String[] args) {
        IntegerProperty num = new SimpleIntegerProperty(10);
        StringBinding desc = new When(num.divide(2).multiply(2).isEqualTo(num)).then("even").otherwise("odd");
        System.out.println(num.get() + " is " + desc.get());
        num.set(19);
        System.out.println(num.get() + " is " + desc.get());
    }
}
Paste_Image.png

Binding Utility Class

Bingdings 類中包含之前提及全部流式API(諸如add,sustract,multiply,divide,concat,eqaul 等等).如果你不喜歡用流式API的寫法,也可以用通過調用Bindings的方法的來滿足你創建所需的binding.

public class BindingsClassTest {
    public static void main(String[] args) {
        DoubleProperty radius = new SimpleDoubleProperty(7.0);
        DoubleProperty area = new SimpleDoubleProperty(0.0);

        // Bind area to an expression that computes the area of the circle
        area.bind(Bindings.multiply(Bindings.multiply(radius, radius), Math.PI));
        // Create a string expression to describe the circle
        StringExpression desc = Bindings.format(Locale.US, "Radius = %.2f, Area = %.2f", radius, area);
        System.out.println(desc.get());

        // Change the radius
        radius.set(14.0);
        System.out.println(desc.getValue());
    }
}
Paste_Image.png

與UI 之間的binding

講了這么多,如果你看過java fx 源碼, 你猜到java fx 是如何實現UI 與 Model 的 data binding 嗎?
其實java fx ui 類 的所有屬性 基本上是 實現了property接口的對象。
比如 textField的textProperty,再比如

public class ChoicBindingExample extends Application {
  ObservableList cursors = FXCollections.observableArrayList(
      Cursor.DEFAULT,
      Cursor.CROSSHAIR,
      Cursor.WAIT,
      Cursor.TEXT,
      Cursor.HAND,
      Cursor.MOVE,
      Cursor.N_RESIZE,
      Cursor.NE_RESIZE,
      Cursor.E_RESIZE,
      Cursor.SE_RESIZE,
      Cursor.S_RESIZE,
      Cursor.SW_RESIZE,
      Cursor.W_RESIZE,
      Cursor.NW_RESIZE,
      Cursor.NONE
    ); 
    @Override
    public void start(Stage stage) {
      ChoiceBox choiceBoxRef = ChoiceBoxBuilder.create()
          .items(cursors)
          .build();    
        VBox box = new VBox();
        box.getChildren().add(choiceBoxRef);
        final Scene scene = new Scene(box,300, 250);
        scene.setFill(null);
        stage.setScene(scene);
        stage.show();
        scene.cursorProperty().bind(choiceBoxRef.getSelectionModel().selectedItemProperty());
        
    }
    public static void main(String[] args) {
        launch(args);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • //Clojure入門教程: Clojure – Functional Programming for the J...
    葡萄喃喃囈語閱讀 3,779評論 0 7
  • java筆記第一天 == 和 equals ==比較的比較的是兩個變量的值是否相等,對于引用型變量表示的是兩個變量...
    jmychou閱讀 1,526評論 0 3
  • 【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔...
    葉總韓閱讀 5,167評論 0 41
  • 文 cherry 三歲的時候桌子上放著一顆咸蛋穿著青蛙服的我咿咿呀呀地指著它問奶奶是什么奶奶說那是咸蛋 給你爸爸吃...
    韻之筆閱讀 539評論 0 0