Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce at least one checkbox in a group is selected?

ButtonGroup is meant for radio-buttons and ensures only one in the group is selected, what I need for check-boxes is to ensure at least one, possibly several are selected.

like image 982
Tibi Avatar asked Jan 20 '26 20:01

Tibi


1 Answers

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 is how to use it:

new ButtonGroupAtLeastOne().addAll(checkBox1, checkBox2)

All suggestions are welcome.

like image 131
Tibi Avatar answered Jan 22 '26 12:01

Tibi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!