【发布时间】:2015-09-03 23:18:07
【问题描述】:
我想在我的应用程序中包含这部分,它允许用户添加更多选项(以 JradioButton 的形式)。因此,默认情况下,我会在 JradioButton 中为用户提供一些选项,如果他们添加更多选项(在应用程序的另一部分);我的 Jframe 应该通过 Setup_Equipment_Frame 方法(如下所示)自动添加选项,在该方法中它获取字符串数组,这些字符串基本上是用户添加的选项。我面临一些困难。
代码:
public void Setup_Equipment_frame(String a[]) //String_Array of Newly added options
{
//creating default options
JRadioButton option1 = new JRadioButton("Visual Stadio");
JRadioButton option2 = new JRadioButton("Netbeans");
JRadioButton option3 = new JRadioButton("Eclipse");
//Creating the button group
ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);
//setting the frame layout
setLayout(new FlowLayout());
for(int i=0; i<=a.length-1;i++) //loop for how many new options are added
{
if(a[i] != null) //if the array's current item is not null
{
JRadioButton NewButton1= new JRadioButton(""+a[i]); //Add the Button
add(NewButton1);
}
}
//adding the default options
add(option1);
add(option2);
add(option3);
pack();
}
现在它确实有效。我添加了单选按钮,但是由于添加的按钮的名称都是“NewButton1”,我无法控制它们,我只能访问最后创建的 JRadioButton 和默认按钮。 我不知道用户可能会添加多少新选项。
我的问题是如何自动创建不同名称的 JRadioButton。
如果我的问题或代码令人困惑,我提前道歉。我没那么有经验。
谢谢
更新
感谢您的回答,在您的帮助下,我只需添加一个 JradioButtons 数组即可解决问题
对于那些可能面临同样问题的人,适用于我的代码如下:
已解决:
public void Setup_Equipment_frame(String a[])
{
int number_of_options=1;//number of new options
for(int i=0; i<=a.length-1;i++)
{
if(a[i] != null){
number_of_options++;
}
}
JRadioButton []v=new JRadioButton[number_of_options];
setLayout(new FlowLayout());
for(int z=0; z<=number_of_options-1;z++)
{if(a[z] != null){
{
v[z]=new JRadioButton(a[z]);
add(v[z]);
}
}
}
}
非常感谢
【问题讨论】:
标签: java swing jframe jradiobutton