Binding在fx的使用
Binding的概念
soldPrice = listPrice - discounts + taxes
通過這個表達式,如果你知道listPrice, discounts, taxes, 你是不是很快能計算出soldPrice? 這就是一個binding的關(guān)系,反之如果你知道了一個soldPrice,你能推算出其他3項嗎镀娶?答案是no. 這里為我們揭示了binding中存在方向的概念写穴,是單向 or 雙向。
NumberBinding
- 利用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());
2.或者它依賴的propery更新的時候牙咏,它也會失效
digit1.set(3);
System.out.println("sum.isValid(): " + sum.isValid());
Binding in String
- 直接使用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之間的邏輯方法比較構(gòu)造。
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());
}
}
雙向綁定
雙向綁定霞扬,改變?nèi)魏我环矫林迹紩|發(fā)另一方的改變,給予這種前提(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());
}
}
流式API
流式 API 是Java fx 在Binding提供的福利 API. 通過這些API,可以向DSL 一樣描述 依賴關(guān)系蒋得。
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());
}
}
三元 API 操作
new When(condition).then(value1).otherwise(value2)
condition對象必須實現(xiàn)了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());
}
}
Binding Utility Class
Bingdings 類中包含之前提及全部流式API(諸如add,sustract,multiply,divide,concat,eqaul 等等).如果你不喜歡用流式API的寫法级及,也可以用通過調(diào)用Bindings的方法的來滿足你創(chuàng)建所需的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());
}
}
與UI 之間的binding
講了這么多,如果你看過java fx 源碼额衙, 你猜到j(luò)ava fx 是如何實現(xiàn)UI 與 Model 的 data binding 嗎饮焦?
其實java fx ui 類 的所有屬性 基本上是 實現(xiàn)了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);
}
}