官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 遂溪县| 南开区| 湛江市| 渝中区| 潞西市| 电白县| 木兰县| 西城区| 商洛市| 徐闻县| 鹿泉市| 孟津县| 长治县| 苏尼特右旗| 固镇县| 镇雄县| 白山市| 龙州县| 民丰县| 景洪市| 玉龙| 大宁县| 谷城县| 巴中市| 浪卡子县| 宁海县| 新丰县| 长武县| 余庆县| 临夏市| 阿合奇县| 兴化市| 开原市| 赣榆县| 邳州市| 扎兰屯市| 唐山市| 汉源县| 桦甸市| 托克托县| 中西区|