1 回答
TA贡献1836条经验 获得超4个赞
即使ObjectProperty<Toggle>您的模型中有 a ,您也无法建立双向绑定,因为ToggleGroup.selectedToggle它是只读的。ToggleGroup.selectedToggle您需要通过向属性和模型属性添加侦听器来解决此问题,并在更改时更新更改源以外的属性。
使用 aMap<String, Toggle>将文本转换为要选择的切换。以下示例使用 aTextField来确定属性而不是模型属性来演示行为:输入RadioButton要选择的文本,它将被选中。
@Override
public void start(Stage primaryStage) throws IOException {
ToggleGroup group = new ToggleGroup();
VBox vbox = new VBox();
for (char c = 'a'; c <= 'f'; c++) {
RadioButton radio = new RadioButton(Character.toString(c));
radio.setToggleGroup(group);
vbox.getChildren().add(radio);
}
TextField input = new TextField();
vbox.getChildren().add(input);
// create map mapping from text to corresponding toggle
Map<String, Toggle> map = new HashMap<>();
for (Toggle t : group.getToggles()) {
map.put(((RadioButton) t).getText(), t);
}
StringProperty property = input.textProperty();
InvalidationListener listener = new InvalidationListener() {
// flag preventing circular updating
boolean updating = false;
@Override
public void invalidated(Observable observable) {
if (!updating) {
updating = true;
if (observable == group.selectedToggleProperty()) {
// change as result of user interaction with RadioButton
// update property
RadioButton selectedToggle = (RadioButton) group.getSelectedToggle();
property.set(selectedToggle == null ? "" : selectedToggle.getText());
} else {
// change as result of updating the property
// select corresponding toggle
Toggle toggleToSelect = map.get(property.get());
group.selectToggle(toggleToSelect);
}
updating = false;
}
}
};
property.addListener(listener);
group.selectedToggleProperty().addListener(listener);
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.show();
}
添加回答
举报