Is at least one checkbox selected in the group?

ButtonGroup is for a radio button and ensures that only one in the group is selected, which is what I need for the checkboxes to ensure that at least one is selected, possibly multiple.

+3


source to share


1 answer


My solution was to use a custom 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);
    }
}

      

And here's how to use it:



new ButtonGroupAtLeastOne().addAll(checkBox1, checkBox2)

      

All suggestions are welcome.

+2


source







All Articles