Unselecting RadioButtons in Java Swing

前端 未结 10 1421
鱼传尺愫
鱼传尺愫 2021-01-01 09:06

When displaying a group of JRadioButtons, initially none of them is selected (unless you programmatically enforce that). I would like to be able to put buttons back into tha

相关标签:
10条回答
  • 2021-01-01 09:39

    You can use a click counter:

    private ButtonGroup radioGroup = new javax.swing.ButtonGroup();
    private JRadioButton jRadioBtn1 = new javax.swing.JRadioButton();
    private int clickCount = 0;
    
    private void jRadioBtn1Clicked(java.awt.event.MouseEvent evt) {                                             
        // Remove selection on a second click
        if (jRadioBtn1.isSelected()) {
    
            if (++clickCount % 2 == 0) {
    
                radioGroup.clearSelection();
            }
        }
    }   
    
    0 讨论(0)
  • 2021-01-01 09:43

    In my case I use Jgoodies project to bind GUI components to Java model. The RadioButton component is bound to a field

    class Model {
      private SomeJavaEnum field; // + getter, setter
    }
    

    In such case ButtonGroup.clearSelection doesn't work since the old value still retains in the model. Straightforward solution was to simply setField(null).

    0 讨论(0)
  • 2021-01-01 09:48

    Or you can use Darryl's Select Button Group which doesn't require you to use an "invisible button".

    0 讨论(0)
  • 2021-01-01 09:50

    When you want to deselect, select invisible. For that you add a third invisible button to the button group.

    0 讨论(0)
提交回复
热议问题