javaswingfor-loopradio-buttonbuttongroup

How to populate a ButtonGroup[] array using a for loop


So I have two arrays of JRadioButton[] that I am trying to put into an array of ButtonGroup[]. When I add a single JRadioButton from my array one at a time to a single ButtonGroup, I have no problems. When I use a for-loop to add to an array of ButtonGroup[], there are no syntax errors but I do get a compiler error:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.ButtonGroup.add(javax.swing.AbstractButton)" because "allButtons[x]" is null

I don't mind creating buttonGroups one at a time, but I was just wondering why the first one works and the other doesn't.

The code that works:

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

The code that doesn't work:

    //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 is a String[] array that I use to label the radio buttons.


Solution

  • In this part of your code, you're creating the array of ButtonGroups, but you never initialize each element, so each of them is 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]);
    }
    

    So, inside your for-loop, add this line as the first line

    allButtons[x] = new ButtonGroup();
    

    And then, the rest of your code