JCheckBoxMenuItem only one selected

纵饮孤独 提交于 2019-12-11 06:40:54

问题


So I want to have a JMenu Level with three JCheckBoxMenuItem like Easy, normal and expert. Of course, only one can be checked and if one is checked, it can't be unchecked (enabled(false)) because it's the only one. I want when one JCheck is checked, all others are unchecked.

So it seems easy, but the only solution I found is to do it with a lot of "if" conditions.

Is there a way to do it with a better algorithm ?


回答1:


It sounds like you'd be better off using a JRadioButton since check boxes are generally used for multiple-choice options and radio buttons for a single selection out of many. JRadioButtons can be grouped together using a ButtonGroup which allows only one selected at a time.




回答2:


   public void stateChanged(ChangeEvent e) {

    if (e.getSource() == cb1 && cb1.isSelected()) {
        cb2.setSelected(false);
        cb3.setSelected(false);
    } else if (e.getSource() == cb2 && cb2.isSelected()) {
        cb3.setSelected(false);
        cb1.setSelected(false);
    } else if (e.getSource() == cb3 && cb3.isSelected()) {
        cb1.setSelected(false);
        cb2.setSelected(false);
    }
}



回答3:


i just put all my JCheckBoxMenuItems in an array and every time i select a JCheckBoxMenuItem i call this method

public void clearCheckBoxes(){
for (JCheckBoxMenuItem arrayCB1 : arrayCB) {
if (arrayCB1 != cb) {
arrayCB1.setSelected(false);
} else {
arrayCB1.setSelected(true);
}
        }
}

The annoying part was having to manualy put them in the array,maybe the jMenu class has a method that returns the complete array but i didnt bother looking

        arrayCB[0]=bridgeCB;
        arrayCB[1]=swampCB;
        arrayCB[2]=flowerCB;
        arrayCB[3]=MountainCB;
        arrayCB[4]=Mountain2CB;
        arrayCB[5]=forestCB;
        arrayCB[6]=parisCB;
        arrayCB[7]=roadCB;
        arrayCB[8]=waveCB;
        arrayCB[9]=lakeCB;

just in case , this is how you create the array

JCheckBoxMenuItem [] arrayCB=new JCheckBoxMenuItem[10];

i dont know about that lots of if statements way of doing it



来源:https://stackoverflow.com/questions/20720400/jcheckboxmenuitem-only-one-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!