Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用collection.txt文件中的Map TreeSet对单选按钮进行分组_Java_Swing_Radio Button_Radio Group - Fatal编程技术网

Java 使用collection.txt文件中的Map TreeSet对单选按钮进行分组

Java 使用collection.txt文件中的Map TreeSet对单选按钮进行分组,java,swing,radio-button,radio-group,Java,Swing,Radio Button,Radio Group,我很难弄明白为什么我的单选按钮不能分组。下面是我的代码 for (String color : colors.keySet()) { JRadioButton button = new JRadioButton(color); ButtonGroup group = new ButtonGroup(); group.add(button); button.setOpaque(false); buttonPanel.add(button); button.addAction

我很难弄明白为什么我的单选按钮不能分组。下面是我的代码

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);
}
您的代码已格式化:

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);
}
在循环的每次迭代中,您都会创建一个新的ButtonGroup,因此每个单选按钮都会指定给自己的按钮组。这不是ButtonGroup的工作方式,因为它们要求将所有分组的切换按钮(如JRadioButtons)添加到单个ButtonGroup

解决方案是只创建一个按钮组,在for循环之前创建一个,然后将每个JRadioButton添加到循环内的该组中。例如:

// 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);
}

谢谢…真不敢相信我错过了。