【问题标题】:Remove hbox when unselected取消选中时移除 hbox
【发布时间】:2017-01-14 10:14:42
【问题描述】:

我想创建带有 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);
                        }
                    });

【问题讨论】:

  • 您想隐藏它以便能够再次显示它还是完全删除它?如果是第二种选择,你为什么要这样做?

标签: javafx radio-button root


【解决方案1】:

单选按钮的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...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多