0

How do I get the quantity of all selected JToggleButtons in a ButtonGroup?

ButtonGroup bGroup = new ButtonGroup();
bGreen = new JToggleButton("Green");
bYellow = new JToggleButton("Yellow");
bRed = new JToggleButton("Red");

bGroup.add(bGreen);
bGroup.add(bYellow);
bGroup.add(bRed);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 1
    `quantity of all selected elements in a ButtonGroup`, which one apples or bananas, for better help sooner edit your question with a [SSCCE](http://sscce.org/), otherwise this question is simple un_answerable – mKorbel May 01 '12 at 17:23
  • 3
    I guess he wants to say "how many elements from the ButtonGroup are selected?" – AlexR May 01 '12 at 17:26
  • Yes, how many of the JToggleButtons are selected? – Evgenij Reznik May 01 '12 at 17:27

2 Answers2

3

There are several ways. For example bGroup.getSelection().getSelectedObjects().length. You can also call getElements(), then iterate over enumeration and ask isSelected() for each button. Please refer to API doc.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

You have to add a item listener to each of the toogle

public int counter = 0;
public void itemStateChanged(ItemEvent e) {
    if(e.getStateChange() == ItemEvent.SELECTED)
    {
         counter++;
    }
    else
    {
        counter --;
    } 
}
Nitin Chhajer
  • 2,299
  • 1
  • 24
  • 35