按键绑定到ObservableMap的值

时间:2017-01-30 16:09:19

标签: java javafx binding

JavaFX是否具有绑定类型,其中我提供带有键的可观察映射,并且计算值将始终在键/值对更改时更新?从地图中删除该密钥将导致null值,将其重新添加将追溯该值。

我一直在寻找JavaDoc并找到MapPropertyMapBindingObservableMapValue,但似乎没有任何东西可以用于此目的。

我已经设计了自己的变体,但是想要使用相当安全且经过测试的版本。

1 个答案:

答案 0 :(得分:2)

你可以做到

someObjectProperty.bind(Bindings.createObjectBinding(
    () -> myObservableMap.get(key), myObservableMap);

或者,正如@VGR在评论中指出的那样

someObjectProperty.bind(Bindings.valueAt(someObservableMap, key));

这是使用第二种方法的SSCCE:

import java.util.Arrays;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class BindToObservableMap extends Application {

    private static final String[] keys = {"key1", "key2", "key3"};

    @Override
    public void start(Stage primaryStage) {
        ObservableMap<String, String> map = FXCollections.observableHashMap();
        for (String k : keys) map.put(k, k.replaceAll("key", "value"));

        GridPane grid = new GridPane();
        grid.setHgap(5);
        grid.setVgap(5);
        grid.setPadding(new Insets(10));
        for (int i = 0 ; i < keys.length; i++) {
            grid.add(new Label(keys[i]), 0, i);
            Label boundLabel = new Label();
            boundLabel.textProperty().bind(Bindings.valueAt(map, keys[i]));
            grid.add(boundLabel, 1, i);
        }

        ComboBox<String> keyCombo = new ComboBox<>();
        keyCombo.getItems().setAll(keys);
        TextField valueField = new TextField();
        Button update = new Button("Update");
        EventHandler<ActionEvent> handler = e -> {
            map.put(keyCombo.getValue(), valueField.getText());
            valueField.clear();
            keyCombo.requestFocus();
        };
        valueField.setOnAction(handler);
        update.setOnAction(handler);

        grid.addRow(keys.length, keyCombo, valueField);
        grid.add(update, 0, keys.length + 1);

        Scene scene = new Scene(grid);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}