【发布时间】:2019-01-03 18:36:58
【问题描述】:
我正在尝试使用 swing 库在 java 中进行个性测验。有 5 个问题,每个问题有 3 个可能的答案。现在我正在构建界面,但我正在努力将多组按钮添加到我的 createComponents 方法中。
因此,为了清楚起见并使其更易于阅读,我为我的第一个问题文本制作了一个单独的方法。已经添加了没有问题。但是我遇到了按钮组的问题。我不想加载我的 createComponents 方法,其中包含多行和多行重复添加 Buttongroups 的内容,因为我读到不包括 cmets,方法最多应为 15 行。或者至少对于初学者来说。
所以我为我的按钮组创建了一个单独的方法,然后我尝试将其添加到 createComponents 方法中。这给了我一个错误,说没有合适的方法可以将按钮组添加到我的容器中。
现在我正在我的 createComponent 方法中编写多行代码,以便我可以“正确”添加我的单选按钮。我只回答第一个问题,我的方法中已经有 16 行。有更好,更有效的方法吗?
private void createComponents(Container container){
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
JLabel text = new JLabel("this is the intro text");
container.add((text), BorderLayout.NORTH);
container.add(QuizIntro());
container.add(QuestionOne());
container.add(QuestionOneGroup());
// this throws an error
JRadioButton int1 = new JRadioButton("This is answer choice 1");
JRadioButton ent1 = new JRadioButton("This is answer choice 2");
JRadioButton jb1 = new JRadioButton("This is answer choice 3");
ButtonGroup group = new ButtonGroup();
group.add(int1);
group.add(ent1);
group.add(jb1);
container.add(int1);
container.add(ent1);
container.add(jb1);
// this is the 'correct' way I've been doing it.
}
public ButtonGroup QuestionOneGroup(){
JRadioButton int1 = new JRadioButton("This is answer choice 1");
JRadioButton ent1 = new JRadioButton("This is answer choice 2");
JRadioButton jb1 = new JRadioButton("This is answer choice 3");
ButtonGroup group = new ButtonGroup();
group.add(int1);
group.add(ent1);
group.add(jb1);
return group;
// this is the method I made to add a buttongroup and make my createComponent easier to read.
}
所以我的预期输出只是一个带有问题和 3 个可能的答案选择的准系统窗口,但我收到一个错误,告诉我没有合适的方法。它说“参数不匹配按钮组无法转换为弹出菜单或组件”。
【问题讨论】:
标签: java swing jpanel jradiobutton buttongroup