如何使用 for 循环填充 ButtonGroup[] 数组

问题描述

所以我有两个 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[] 数组,我用它来标记单选按钮。

解决方法

在这部分代码中,您正在创建 ButtonGroups 数组,但您从未初始化每个元素,因此它们中的每一个都是 null

//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();

然后,剩下的代码