【问题标题】:How to do bidirectional binding between a StringProperty and a combobox SelectedItemProperty如何在 StringProperty 和组合框 SelectedItemProperty 之间进行双向绑定
【发布时间】:2019-05-18 13:10:42
【问题描述】:

我想在 StringProperty 和组合框 SelectedItemProperty 之间进行双向绑定。每当组合框的选定项发生更改时,它都应将值反映到 StringProperty。同样,每当 StringProperty 的值发生变化时,它都应该选择组合框中的值。

我们如何进行这种绑定?

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    您不能绑定到SelectedItemProperty,而是将绑定添加到ComboBoxValueProperty

    comboBox.valueProperty().bindBidirectional(stringProperty);
    

    这里有一个完整的例子来演示:

    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.Label;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class BiBindingExample extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
    
            // Simple interface
            VBox root = new VBox(5);
            root.setPadding(new Insets(10));
            root.setAlignment(Pos.CENTER);
    
            // Our StringProperty
            StringProperty stringProperty = new SimpleStringProperty();
    
            // Label to display our StringProperty
            Label label = new Label();
            label.textProperty().bind(stringProperty);
    
            // The ComboBox
            ComboBox<String> comboBox = new ComboBox<>();
            comboBox.getItems().addAll("Zero", "One", "Two", "Three", "Four", "Five");
    
            // Bind the ComboBox value to that of the StringProperty, and vice versa
            comboBox.valueProperty().bindBidirectional(stringProperty);
    
            // A button to programmatically change the StringProperty
            Button button = new Button("Return to Zero");
            button.setOnAction(e -> stringProperty.set("Zero"));
    
            root.getChildren().addAll(comboBox, label, button);
    
            // Show the Stage
            primaryStage.setWidth(300);
            primaryStage.setHeight(300);
            primaryStage.setScene(new Scene(root));
            primaryStage.show();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2015-10-25
      • 2020-01-15
      • 2016-02-12
      相关资源
      最近更新 更多