我有一组 JRadioButtons 和一个 JCheckBox。如果未选中 JCheckBox,则 JRadioButtons 应禁用并重置,反之亦然。我遇到的问题是,无论我是否检查 JCheckBox,JRadioButtons 都会保持禁用状态。
此外,在继续编写代码之前,不要介意空布局和缺少不同的类。我很快制作了一个测试项目,以减少我必须粘贴到此处的代码量。
package test;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 261);
frame.getContentPane().add(panel);
JCheckBox ckbxTestCheckBox = new JCheckBox("Test Check Box");
ckbxTestCheckBox.setBounds(7, 7, 99, 23);
panel.add(ckbxTestCheckBox);
JRadioButton rdbtnTestRadioButton1 = new JRadioButton("Test Radio Button 1");
rdbtnTestRadioButton1.setBounds(7, 34, 121, 23);
panel.add(rdbtnTestRadioButton1);
JRadioButton rdbtnTestRadioButton2 = new JRadioButton("Test Radio Button 2");
rdbtnTestRadioButton2.setBounds(7, 61, 121, 23);
panel.add(rdbtnTestRadioButton2);
JRadioButton rdbtnTestRadioButton3 = new JRadioButton("Test Radio Button 3");
rdbtnTestRadioButton3.setBounds(7, 88, 121, 23);
panel.add(rdbtnTestRadioButton3);
JRadioButton rdbtnTest[] = {rdbtnTestRadioButton1, rdbtnTestRadioButton2, rdbtnTestRadioButton3};
ButtonGroup btnGrpTest = new ButtonGroup();
for(int i = 0; i < rdbtnTest.length; i++){
btnGrpTest.add(rdbtnTest[i]);
}
if(!ckbxTestCheckBox.isSelected()){
for(int i = 0; i < rdbtnTest.length; i++){
rdbtnTest[i].setEnabled(false);
rdbtnTest[i].setSelected(false);
}
} else { //Is this part even necessary?
for(int i = 0; i < rdbtnTest.length; i++){
rdbtnTest[i].setEnabled(true);
}
}
}
}
最佳答案
正如 @zubergu 指出的,您的逻辑必须编写在复选框的 ItemListener
内,否则就没有意义。
此外,如果没有 if
和 else
block ,您的逻辑可以得到相当简化:
ckbxTestCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
for(int i = 0; i < rdbtnTest.length; i++){
rdbtnTest[i].setEnabled(!ckbxTestCheckBox.isSelected());
if(!ckbxTestCheckBox.isSelected())
rdbtnTest[i].setSelected(false);
}
}
});
请注意,对于 JCheckBox
,也可以使用 ActionListener
而不是 ItemListener
。
关于java - JCheckBox 启用/禁用 JRadioButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660068/