ButtonGroup はラジオ ボタン用であり、グループ内で 1 つだけが選択されていることを確認します。チェック ボックスに必要なのは、少なくとも 1 つ、場合によっては複数が選択されていることを確認することです。
質問する
1526 次
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 に答える