【问题标题】:How to deselect a radiobutton other than having it in a toggleGroup witth another radiobutton如何取消选择一个单选按钮,而不是将其与另一个单选按钮放在一个切换组中
【发布时间】:2019-09-03 09:54:09
【问题描述】:

我有 5 个单选按钮(A、B、C、D、E),每个 2 在一个切换组中(例如 A 和 B 在一个切换组中,C 和 D 在一个切换组中),第五个是孤独的。我希望如果我选择 A 和 C 然后选择 E,则 A 和 C 都被取消选择。我尝试使用 .setSelected(false) 但它似乎不起作用。是否有其他功能,或者我可以在两个切换组中使用 E?如果是,如何? 谢谢。

【问题讨论】:

  • 在我看来,E 根本不应该是一个单选按钮——它应该是一个复选框
  • 没关系,我只想知道为什么 setSelected 不起作用。
  • 我无法重现该问题。请edit 您的问题添加minimal reproducible example 演示该问题。包括您使用的 JavaFX 版本。

标签: java user-interface javafx radio-button scenebuilder


【解决方案1】:

可能有更好的解决方案,但这可以解决您的问题:
- 在 initialize 方法中为每个 RadioButton 创建事件,检查它们的值(并根据它们的选择状态添加您的代码):

aRadioButton.selectedProperty().addListener((observable, oldValue, newValue) -> {
    //if RadioButton is selected
    if (newValue) {
        //check if other RadioButtons are selected
        if(bRadioButton.isSelected()) {
             //add your code
             // deselect it using:
             bRadioButton.setSelected(false);
        } else {
        // aRadioButton is deselected
        //add your code
     }
}

- 或者从 fxml 创建一个事件

@FXML
private void aRadioButton(ActionEvent event) { 
    //this will change the state of RadioButton
    //to preserve deselection from this event use:
    if(!aRadioButton.isSelected()) {
        aRadioButon.setSelected(true);    
    }
    //add your code here
}

这种方式不包括 ToggleGroup,您必须管理 RadioButton 的选择状态。

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 2011-11-05
    • 2019-03-25
    • 2016-09-24
    • 1970-01-01
    • 2017-08-29
    • 2017-07-19
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多