2

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.

Sukhbir
  • 553
  • 8
  • 23

1 Answers1

2

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;
}
SSD
  • 359
  • 1
  • 3
  • 15