如何在下面的代码中对复选框进行分组?以及如何在Java中获取其复选框的选定值?

// CHECKBOXES
JCheckBox cb_CCP = new JCheckBox("Chinese Cultural Places");
JCheckBox cb_HandCP = new JCheckBox("Heritage & Culture Places");
JCheckBox cb_HCentres = new JCheckBox("Heritage Centres");
JCheckBox cb_HMuseums = new JCheckBox("Heritage Museums");
JCheckBox cb_ICP = new JCheckBox("Indian Cultural Places");
JCheckBox cb_MCP = new JCheckBox("Malay Cultural Places\r\n");
JCheckBox cb_HTrails = new JCheckBox("Heritage Trails");
JCheckBox cb_PCP = new JCheckBox("Peranakan Cultural Places");

最佳答案

要分组,您需要一个ButtonGroup

ButtonGroup bg = new ButtonGroup();
bg.add(cb_CCP);
bg.add(cb_HandCP);
.. and so on


您添加要分组的所有复选框。通过分组,您只能选择一个。

要检查选择了哪一个,它应该在您的监听器中

if (cb_CCP.isSelected()){
    String s = cb_CCP.getText();
    // do something
} else if (cb_HandCP.isSelected()){
    // do something
} else if (.....){
    ...
}

关于java - 将复选框分组并在Java中获取复选框的选定值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20350286/

10-10 10:03