开发者

Multi selection problem on Swing JCheckbox

I have a list of checkboxes, but I can not make multi selection from 开发者_如何学Gothis list, it disables the previous selection when I check a new box. how can I change my code? or if it looks ok and by accident I do something wrong somewhere else in my code.

public JPanel createMultiMenu(ArrayList<String> domainItems) {

    checkBoxMenuPanel = new JPanel();
    checkBoxMenuPanel.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;
    gbc.anchor = GridBagConstraints.WEST;

    ButtonGroup group = new ButtonGroup();
    for (String item : domainItems) {
        JCheckBox checkBox = new JCheckBox(item);
        group.add(checkBox);
        checkBoxMenuPanel.add(checkBox,gbc);        
    }
    return checkBoxMenuPanel;
}


That is the way a ButtonGroup works, you can select any button in the group but only 1 can be selected at a time. Also generally a JRadioButton is used for this.

If you want to be able to select multiple checkboxes, then don't use a ButtonGroup.


The problem is that you are using ButtonGroup, which treats objects placed in it as radiobuttons (you can only select one at a time).

Instead try just adding them to the JPanel.

public JPanel createMultiMenu(ArrayList<String> domainItems) {

    checkBoxMenuPanel = new JPanel();
    checkBoxMenuPanel.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;
    gbc.anchor = GridBagConstraints.WEST;


    for (String item : domainItems) {
        JCheckBox checkBox = new JCheckBox(item);
        checkBoxMenuPanel.add(checkBox, gbc);        
    }
    return checkBoxMenuPanel;
}

Something like that.


May be you need JRadioButtons? Use ButtonGroup and add all radiobuttons in the group. After that if you select any of them previously selected looses the selected state.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜