3

ButtonGroup 用于单选按钮并确保仅选择组中的一个,我需要复选框以确保至少选择一个,可能是几个。

4

1 回答 1

2

我的解决方案是使用自定义 ButtonGroup:

/**
 * A ButtonGroup for check-boxes enforcing that at least one remains selected.
 * 
 * When the group has exactly two buttons, deselecting the last selected one
 * automatically selects the other.
 * 
 * When the group has more buttons, deselection of the last selected one is denied.
 */
public class ButtonGroupAtLeastOne extends ButtonGroup {

    private final Set<ButtonModel> selected = new HashSet<>();

    @Override
    public void setSelected(ButtonModel model, boolean b) {
        if (b && !this.selected.contains(model) ) {
            select(model, true);
        } else if (!b && this.selected.contains(model)) {
            if (this.buttons.size() == 2 && this.selected.size() == 1) {
                select(model, false);
                AbstractButton other = this.buttons.get(0).getModel() == model ?
                        this.buttons.get(1) : this.buttons.get(0);
                select(other.getModel(), true);
            } else if (this.selected.size() > 1) {
                this.selected.remove(model);
                model.setSelected(false);
            }
        }
    }

    private void select(ButtonModel model, boolean b) {
        if (b) {
            this.selected.add(model);
        } else {
            this.selected.remove(model);
        }
        model.setSelected(b);
    }

    @Override
    public boolean isSelected(ButtonModel m) {
        return this.selected.contains(m);
    }

    public void addAll(AbstractButton... buttons) {
        for (AbstractButton button : buttons) {
            add(button);
        }
    }

    @Override
    public void add(AbstractButton button) {
        if (button.isSelected()) {
            this.selected.add(button.getModel());
        }
        super.add(button);
    }
}

以下是如何使用它:

new ButtonGroupAtLeastOne().addAll(checkBox1, checkBox2)

欢迎所有建议。

于 2013-02-15T10:18:29.910 回答