jion
jion

Reputation: 382

How to create ButtonGroup of JToggleButton's that allows to deselect the actual option?

That's it. I need to create a ButtonGroup that allows to select a option or, if the user click on the selected option, deselect the item (nothing will be selected) and, of course, capture the event to do something.

Upvotes: 10

Views: 8426

Answers (5)

Jeff Storey
Jeff Storey

Reputation: 57192

This shows exactly how to do that https://dzone.com/articles/unselect-all-toggle-buttons

Upvotes: 5

Mark Jeronimus
Mark Jeronimus

Reputation: 9543

I noticed weird behavior when doing button.setSelected(false) on a button/checkbox that is not selected. It deselected everything as if I deselected something.

I fixed it this way:

public class NoneSelectedButtonGroup extends ButtonGroup {

  @Override
  public void setSelected(ButtonModel model, boolean selected) {
    if (selected) {
      super.setSelected(model, selected);
    } else if (getSelection() != model) {
      clearSelection();
    }
  }
}

Upvotes: 1

Padde
Padde

Reputation: 26

Solution for pre java 1.6

public class NoneSelectedButtonGroup extends ButtonGroup {
    private AbstractButton hack;

    public NoneSelectedButtonGroup() {
        super();
        hack = new JButton();
        add(hack);
    }

    @Override
    public void setSelected(ButtonModel model, boolean selected) {
        super.setSelected(selected ? model : hack.getModel(), true);
    }
}

Upvotes: 0

Stalin Gino
Stalin Gino

Reputation: 622

Capture the event to do something. Also do the below.

@Override
public void actionPerformed(ActionEvent e) {
    ((JToggleButton)e.getSource()).setSelected(false);
}

EDIT: But there is no ButtonGroup involved.

Upvotes: 0

remi
remi

Reputation: 3988

Just in case Jeff's link is broken in the future, here's what's described: you need to subclass ButtonGroup to allow a no-selection, and add your buttons to this buttongroup.

public class NoneSelectedButtonGroup extends ButtonGroup {

  @Override
  public void setSelected(ButtonModel model, boolean selected) {
    if (selected) {
      super.setSelected(model, selected);
    } else {
      clearSelection();
    }
  }
}

Upvotes: 13

Related Questions