簡體   English   中英

如何獲取JRadioButton的ButtonGroup

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM