Question

I'm having a hard time trying to figure out why my radio buttons will not group. Below is my code.

for (String color : colors.keySet()) {
  JRadioButton button = new JRadioButton(color);
  ButtonGroup group = new ButtonGroup();
  group.add(button);
  button.setOpaque(false);
  buttonPanel.add(button);
  button.addActionListener(listener);
}
Was it helpful?

Solution

Your code formatted:

for (String color : colors.keySet()) {
  JRadioButton button = new JRadioButton(color);
  ButtonGroup group = new ButtonGroup();
  group.add(button);
  button.setOpaque(false);
  buttonPanel.add(button);
  button.addActionListener(listener);
}

You're creating a new ButtonGroup with each iteration of the loop, and so each radio button is assigned to its own button group. This is not how ButtonGroups work as they require that all of the grouped toggle buttons (such as JRadioButtons) be added to a single ButtonGroup.

The solution is to create only one ButtonGroup, to do this before the for-loop, and then add each JRadioButton to that group inside of the loop. For example:

// do this *before* the for-loop
ButtonGroup group = new ButtonGroup();

for (String color : colors.keySet()) {
  JRadioButton button = new JRadioButton(color);
  // ButtonGroup group = new ButtonGroup(); // not *inside* the for loop
  group.add(button);  // then use it here
  button.setOpaque(false);
  buttonPanel.add(button);
  button.addActionListener(listener);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top