java - 添加多个按钮组的更有效方法
问题描述
我正在尝试使用 swing 库在 java 中进行个性测验。有 5 个问题,每个问题有 3 个可能的答案。现在我正在构建界面,但我正在努力将多组按钮添加到我的 createComponents 方法中。
因此,为了清楚起见并使其更易于阅读,我为我的第一个问题文本制作了一个单独的方法。已经添加了没有问题。但是我遇到了按钮组的问题。我不想加载我的 createComponents 方法,其中包含多行和多行重复添加 Buttongroups 的内容,因为我读到,不包括注释,方法最多应为 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 个可能的答案选择的准系统窗口,但我收到一个错误,告诉我没有合适的方法。它说“参数不匹配按钮组无法转换为弹出菜单或组件”。
解决方案
您只能添加Components
到Container
.
AButtonGroup
不是Component
.
AButtonGroup
用于指示选择了一组组件中的哪个组件。您仍然需要将每个单独的单选按钮添加到面板。
你的代码应该是这样的:
//public ButtonGroup QuestionOneGroup()
public JPanel 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;
JPanel panel = new JPanel();
panel.add( int1 );
panel.add( ent1 );
panel.add( jb1 );
return panel;
}
阅读 Swing 教程中有关如何使用单选按钮的部分以获取更多信息和工作示例。
推荐阅读
- javascript - 如何根据按钮单击更改页面样式
- amazon-web-services - Route53 在传输 dns 记录后声称没有名称服务器
- php - PHP - 在未定义的数组索引上使用 += 运算符
- android - 在没有新的静态/动态快捷方式的情况下获取快捷方式
- angular - 如何从现有的 Angular cli 项目中删除所有规范文件
- c# - C#如何在不知道长度的情况下读取某些属性
- python - bind.() 函数只发送最后一个参数
- php - 如何从预定义的 html 单选输入中获取数组
- markdown - 在 Typora 中显示数学符号
- c# - 如何在 ExecuteReader 中有两个 executeNonQuery