【发布时间】:2021-05-01 02:15:36
【问题描述】:
所以我有两个JRadioButton[] 数组,我试图将它们放入ButtonGroup[] 数组中。当我从我的数组中一次添加一个JRadioButton 到一个ButtonGroup 时,我没有问题。当我使用 for 循环添加到 ButtonGroup[] 的数组时,没有语法错误,但我确实收到了编译器错误:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.ButtonGroup.add(javax.swing.AbstractButton)" because "allButtons[x]" is null
我不介意一次创建一个buttonGroups,但我只是想知道为什么第一个有效而另一个无效。
有效的代码:
//creates radio buttons
JRadioButton[] profButtons = new JRadioButton[profs.length];
JRadioButton[] expButtons = new JRadioButton[profs.length];
for(int i=0; i<profs.length; i++)
{
profButtons[i] = new JRadioButton(profs[i]);
expButtons[i] = new JRadioButton(profs[i]);
}
//makes the radio button groups.
ButtonGroup acrGroup = new ButtonGroup();
acrGroup.add(profButtons[0]);
acrGroup.add(expButtons[0]);
不起作用的代码:
//creates radio buttons
JRadioButton[] profButtons = new JRadioButton[profs.length];
JRadioButton[] expButtons = new JRadioButton[profs.length];
for(int i=0; i<profs.length; i++)
{
profButtons[i] = new JRadioButton(profs[i]);
expButtons[i] = new JRadioButton(profs[i]);
}
//makes the radio button groups.
ButtonGroup[] allButtons = new ButtonGroup[profs.length];
for(int x=0; x<profs.length; x++)
{
allButtons[x].add(profButtons[x]);
allButtons[x].add(expButtons[x]);
}
profs 是一个 String[] 数组,我用它来标记单选按钮。
【问题讨论】:
标签: java swing for-loop radio-button buttongroup