我有一组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);
}
}
}
}发布于 2016-06-06 14:39:28
正如@zubergu所指出的,您的逻辑必须写在复选框的ItemListener中,否则就没有意义了。
此外,没有if和else块,您的逻辑也可以相当简化:
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也可以工作。
https://stackoverflow.com/questions/37660068
复制相似问题