这就是我从包含名为"txtName"的字符串变量的类 FamilyMember 中取消绑定双向的方式。我解绑旧值并清除它,然后绑定新值。
解绑:
((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());
但是我对如何为组合框执行此操作感到困惑。我的组合框用于选择具有 3 个选项作为字符串的性别,(组合框(、男性、女性和其他。如何使用具有字符串属性的组合框来实现上述目标?
控制器类:
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>