简体   繁体   中英

How to get ButtonGroup of JRadioButton

In a project, I added ItemListener to a group of JcheckBox and JRadioButtons.

And I want that when a user click on already selected JRadioButton, it gets deselected.

For this only method I know is getting Corresponding ButtonGroup and then calling clearSelection() method. But in itemStateChanged() method I have JtoggleButton option=(JtoggleButton)event.getSource();

So option refers to either JRadioButton or JcheckBox. I have searched but I cannot able to find a method to get ButtonGroup for a JRadioButton.

you can use getSource and check with instanceof . If it is a JRadioButton cast it to JRadioButton and set selected to false. Same thing for JCheckBox

if(event.getSource instanceof JRadioButton){

 JRadioButton  btn=(JRadioButton)    event.getSource();
    btn.setSelected=false;
}
else if (event.getSource instanceof JCheckBox){

  JCheckBox chb=  (JCheckBox)    event.getSource();
    chb.setSelected=false;
}

IF you want to deselect already selected one you can add a condition like below

if(event.getSource instanceof JRadioButton){

  JRadioButton  btn=(JRadioButton)    event.getSource();
  if(btn.isSelected())
     btn.setSelected=false;
}
else if (event.getSource instanceof JCheckBox){   
  JCheckBox chb=  (JCheckBox)    event.getSource();
  if(chb.isSelected())
     chb.setSelected=false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM