所以我有两个要放入ButtonGroup[]数组的JRadioButton[]数组。当我将阵列中的单个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[]数组,我用它来标记单选按钮。
发布于 2021-05-01 02:15:37
在这部分代码中,您创建了ButtonGroups数组,但从未初始化每个元素,因此每个元素都为空
//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]);
}因此,在您的for-loop中,将此行添加为第一行
allButtons[x] = new ButtonGroup();然后,剩下的代码
https://stackoverflow.com/questions/67338610
复制相似问题