java是添加多个按钮组的更有效方法
我正试图使用swing库在java中做一个个性测验。有5个问题,每个问题有3个可能的答案。现在我正在构建界面,但我正在努力将多组按钮添加到我的createComponents方法中
因此,为了清晰易懂,我为我的第一个问题文本制定了一个单独的方法。这一点没有问题。但我遇到了按钮组的问题。我不想在我的createComponents方法中加载多行重复的AddButtonGroups内容,因为我读到,除去注释,方法的最大长度应该是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个可能答案选择的基本窗口,但我得到一个错误,告诉我没有合适的方法。它说“参数不匹配按钮组无法转换为弹出菜单或组件”
# 1 楼答案
只能将
Components
添加到Container
A
ButtonGroup
不是AComponent
一个
ButtonGroup
用于指示选择了一组组件中的哪个组件。您仍然需要将每个单选按钮添加到面板中你的代码应该是这样的:
阅读Swing教程中关于How to Use Radio Buttons的部分,了解更多信息和工作示例