把多个ButtonGroups放在一个JFrame中
问题描述:
我想把多个JButton放在一个框架上,使用ButtonGroup。我不得不把3组按钮放在一个框架上,彼此分离。把多个ButtonGroups放在一个JFrame中
下面的代码将创建一个按钮,而是被分隔的,他们似乎是“删除”对方。
我期待看到的按钮有独立的组,每组4个按钮。
的方法接受的“问题”的对象一个ArrayList,它看起来像这样:
public class Question {
private String _question;
private String _option1;
private String _option2;
private String _option3;
private String _option4;
}
这里的方法。它在一个类从另一个类“DisplayOnPanel”中继承一个帧以在同一帧上设置面板。 “这” 指的是框架:
public void addButtonstoFrame(ArrayList<Question> q){
ArrayList<ButtonGroup> BG = new ArrayList<>();
ArrayList<JPanel> JP = new ArrayList<>();
JLabel question1 = new JLabel();
int j=0;
for (int i = 0; i <q.size() ; i++) {
BG.add(new ButtonGroup());
JP.add(new JPanel());
JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
BG.get(j).add(option1);
BG.get(j).add(option2);
BG.get(j).add(option3);
BG.get(j).add(option4);
JP.get(j).add(option1);
JP.get(j).add(option2);
JP.get(j).add(option3);
JP.get(j).add(option4);
this.setLayout(new BorderLayout()); //this referes to a frame
this.add(JP.get(j)); //this referes to a frame
JP.get(i).setLocation(j+10,j+10);
JP.get(j).setVisible(true);
this.setVisible(true);//this referes to a frame
j++;
}
}
,结果是只有4 butoons,而不是12:
谢谢!
答
首先,变量名不应该以大写字母开头。
JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
BG.get(j).add(option1);
BG.get(j).add(option2);
BG.get(j).add(option3);
BG.get(j).add(option4);
JP.get(j).add(option1);
JP.get(j).add(option2);
JP.get(j).add(option3);
JP.get(j).add(option4);
一个组件只能属于一个父容器。
将按钮添加到“JP”包含时,将其从“BG”容器中移除。
因此,您需要为每个单选按钮创建4个以上的实例。
请始终包含一个完整的代码示例(SSCCE)。 – Amber
实际上它有很多代码,并且我被告知最后一次不要发布我的整个代码:-( – Alan
您现在没有被告知要发布整个代码。为了更快地获得更好的帮助,请发布[MCVE]或[ Short,Self Contained,Correct Example](http://www.sscce.org/)。@Amber的提示:'[mcve]'在评论中自动扩展为[mcve]。 –