未选中时删除 hbox

Remove hbox when unselected

我想创建包含 3 个单选按钮(comm、med、all)的菜单。 Where for example Comm button should create hbox, but when the other option is selected, this hbox should disapear, but it wont.

谁能告诉我正确的方向? 十分感谢。

这是我得到的:

comm.setOnAction(new EventHandler<ActionEvent>() {
                        @Override public void handle(ActionEvent e) {
                            if(comm.isSelected())
                                root.add(commBox, 0,1);
                            else if(med.isSelected()||all.isSelected())
                                root.getChildren().remove(commBox);
                        }
                    });

当对该按钮执行操作时,将调用单选按钮的onAction 处理程序。选择同一切换组中的 其他按钮 之一时,单选按钮将取消选择。因此,当取消选择按钮时,您的处理程序不会被调用。

改为使用 selectedProperty 注册侦听器:

comm.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
    if (isNowSelected) {
        root.add(commBox, 0,1);
    } else {
        root.getChildren().remove(commBox);
    }
});

或者,您可以使用切换组注册一个侦听器:

// assuming the following existing code, or its equivalent:
ToggleGroup toggleGroup = new ToggleGroup();
comm.setToggleGroup(toggleGroup);
med.setToggleGroup(toggleGroup);
all.setToggleGroup(toggleGroup);

// then this will work:
toggleGroup.selectedToggleProperty().addListener((obs, oldToggle, newToggle) -> {
    if (newToggle == comm) {
        root.add(commBox, 0, 1);
    } else {
        root.getChildren().remove(commBox);
    }
    // maybe more logic here to handle med or all selected...
});