首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用for循环填充ButtonGroup[]数组

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

Stack Overflow用户
提问于 2021-05-01 02:11:56
回答 1查看 48关注 0票数 0

所以我有两个要放入ButtonGroup[]数组的JRadioButton[]数组。当我将阵列中的单个JRadioButton一次一个添加到单个ButtonGroup中时,没有任何问题。当我使用一个for循环来添加一个ButtonGroup[]数组时,没有语法错误,但是我得到了一个编译器错误:

代码语言:javascript
复制
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.ButtonGroup.add(javax.swing.AbstractButton)" because "allButtons[x]" is null

我不介意一次创建一个buttonGroups,但我只是想知道为什么第一个可以工作,而另一个不能。

可以工作的代码:

代码语言:javascript
复制
    //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]);

不起作用的代码:

代码语言:javascript
复制
    //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[]数组,我用它来标记单选按钮。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-01 02:15:37

在这部分代码中,您创建了ButtonGroups数组,但从未初始化每个元素,因此每个元素都为空

代码语言:javascript
复制
//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中,将此行添加为第一行

代码语言:javascript
复制
allButtons[x] = new ButtonGroup();

然后,剩下的代码

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67338610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档