【问题标题】:How to populate a ButtonGroup[] array using a for loop如何使用 for 循环填充 ButtonGroup[] 数组
【发布时间】: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


    【解决方案1】:

    在这部分代码中,您正在创建 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();
    

    然后,剩下的代码

    【讨论】:

      猜你喜欢
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多