[英]How to get ButtonGroup of JRadioButton
In a project, I added ItemListener to a group of JcheckBox and JRadioButtons. 在一个项目中,我将ItemListener添加到一组JcheckBox和JRadioButtons中。
And I want that when a user click on already selected JRadioButton, it gets deselected. 我希望当用户单击已选择的JRadioButton时,它会被取消选择。
For this only method I know is getting Corresponding ButtonGroup and then calling clearSelection() method. 对于这个唯一的方法,我知道要获取对应的ButtonGroup,然后调用clearSelection()方法。 But in itemStateChanged() method I have JtoggleButton option=(JtoggleButton)event.getSource(); 但是在itemStateChanged()方法中,我有JtoggleButton option =(JtoggleButton)event.getSource();
So option refers to either JRadioButton or JcheckBox. 因此,选项是指JRadioButton或JcheckBox。 I have searched but I cannot able to find a method to get ButtonGroup for a JRadioButton. 我已经搜索过,但是我找不到能够为JRadioButton获取ButtonGroup的方法。
you can use getSource
and check with instanceof
. 您可以使用getSource
并使用instanceof
检查。 If it is a JRadioButton
cast it to JRadioButton
and set selected
to false. 如果它是JRadioButton
将它转换为JRadioButton
和设定selected
为false。 Same thing for JCheckBox
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.