我的程序中有多个复选框。我希望用户仅选择3个复选框,并且选中其中3个复选框时,应禁用其他复选框。此外,如果未选中任何一项,则应启用所有其他选项。
最佳答案
这是带有几乎完整源代码的解决方案:
public class TestProgram {
public static JCheckBox[] checkList = new JCheckBox[10];
public static void main(String[] args) {
Listener listener = new Listener();
for (int i = 0; i < 10; ++i) {
checkList[i] = new JCheckBox("CheckBox-" + i);
checkList[i].addItemListener(listener);
}
//
// The rest of the GUI layout job ...
//
}
static class Listener implements ItemListener {
private final int MAX_SELECTIONS = 3;
private int selectionCounter = 0;
@Override
public void itemStateChanged(ItemEvent e) {
JCheckBox source = (JCheckBox) e.getSource();
if (source.isSelected()) {
selectionCounter++;
// check for max selections:
if (selectionCounter == MAX_SELECTIONS)
for (JCheckBox box: checkList)
if (!box.isSelected())
box.setEnabled(false);
}
else {
selectionCounter--;
// check for less than max selections:
if (selectionCounter < MAX_SELECTIONS)
for (JCheckBox box: checkList)
box.setEnabled(true);
}
}
}
}