[英]How to get ButtonGroup of JRadioButton
在一個項目中,我將ItemListener添加到一組JcheckBox和JRadioButtons中。
我希望當用戶單擊已選擇的JRadioButton時,它會被取消選擇。
對於這個唯一的方法,我知道要獲取對應的ButtonGroup,然后調用clearSelection()方法。 但是在itemStateChanged()方法中,我有JtoggleButton option =(JtoggleButton)event.getSource();
因此,選項是指JRadioButton或JcheckBox。 我已經搜索過,但是我找不到能夠為JRadioButton獲取ButtonGroup的方法。
您可以使用getSource
並使用instanceof
檢查。 如果它是JRadioButton
將它轉換為JRadioButton
和設定selected
為false。 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(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.