如何在ComboBox javaFX中为StringProperty绑定和取消绑定?

时间:2020-06-01 11:45:47

标签: javafx combobox binding

这是我如何从包含名为'txtName'的字符串变量的FamilyMember类中取消BiDirect的绑定。我取消绑定旧值并清除它,然后绑定新值。

解除绑定:

((TreeItem<FamilyMember>)oldValue).getValue().nameProperty().unbindBidirectional(txtName.textProperty());
txtName.clear();

绑定:

txtName.setText(((TreeItem<FamilyMember>)newValue).getValue().nameProperty().getValue());
((TreeItem<FamilyMember>)newValue).getValue().nameProperty().bindBidirectional(txtName.textProperty());

但是我对于如何为ComboBox执行此操作感到困惑。我的组合框用于选择带有3个选项的性别作为字符串,(组合框),男,女和其他。如何使用带有String属性的ComboBox来实现上述目的?

1 个答案:

答案 0 :(得分:0)

控制器类:

package sample;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;

import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    @FXML
    private ComboBox<String> genderComboBox;
    @FXML
    private Label selectedGenderLabel;

    private Random random = new Random();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Add items:
        genderComboBox.getItems().addAll("Male", "Female", "Other");

        // Bind selection of combo box to string property:
        selectedGenderLabel.textProperty().bind(genderComboBox.valueProperty());
    }

    @FXML
    public void handleUnbindBtnClick() {
        // Un-bind and clear:
        selectedGenderLabel.textProperty().unbind();
        selectedGenderLabel.setText("");
    }

    @FXML
    public void handleBindBtnClick() {
        // Make a random selection:
        genderComboBox.getSelectionModel().select(random.nextInt(3));

        // Re-bind:
        selectedGenderLabel.textProperty().bind(genderComboBox.valueProperty());
    }
}

FXML文件:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <ComboBox fx:id="genderComboBox" />
      <Label text="Selected Gender:" />
      <Label fx:id="selectedGenderLabel" />
      <Button mnemonicParsing="false" onAction="#handleUnbindBtnClick" text="Unbind" />
      <Button mnemonicParsing="false" onAction="#handleBindBtnClick" text="Bind" />
   </children>
</VBox>