上QQ阅读APP看书,第一时间看更新
Introducing the Binding API
The Binding API allows you to simplify listeners to just one line of code:
// chapter3/basics/WidthBinding.java
public void start(Stage stage) {
Label lblWidth = new Label();
lblWidth.textProperty().bind(stage.widthProperty().asString());
stage.setScene(new Scene(new StackPane(lblWidth), 200, 150));
stage.show();
}
Let's take a closer look at the binding code:
lblWidth // object we want to change
.textProperty() // property of the object to be changed
.bind( // bind() call
stage // object we want to monitor
.widthProperty() // property of the monitored object we want to track
.asString()); // assigning Double value to a String property
The bind() method comes from the base Property interface, which has the following API methods:
- bind (ObservableValue<? extends T> observable): Binds a Property to Observable.
- unbind (): Stops binding.
- boolean isBound (): Checks whether a Property is already bound. It's important as only one binding connection can be set for a Property, although this connection can be made as complex as you need, as will be shown later in the chapter.
- bindBidirectional (Property<T> other): Ties two properties together in both directions.
- unbindBidirectional (Property<T> other): Stops the bidirectional binding.
Bidirectional binding connects two properties, essentially making them always have the same value.
Consider the following example:
// chapter3/basics/BidirectionalBindingDemo.java
public void start(Stage stage) {
Slider s1 = new Slider(0, 100, 40);
Slider s2 = new Slider(0, 100, 40);
s2.setOrientation(Orientation.VERTICAL);
s1.valueProperty().bindBidirectional(s2.valueProperty());
VBox root = new VBox(5, s1, s2);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(20));
stage.setScene(new Scene(root, 200, 150));
stage.show();
}
The preceding code creates two sliders. You can drag either of them and the other one will mimic the movement: