Search code examples
javaswingjradiobuttonbuttongroup

ButtonGroup null pointer exception


I've created a method that will clear any previous selections made to my ButtonGroup that is comprised of radio buttons

    public void resetRadioButtons() {

    if (group.getSelection() != null) {
        group.clearSelection();
    }
    else {

    }

}

The group is instantiated here:

        final ButtonGroup group = new ButtonGroup();
        group.add(radioAnswer1);
        group.add(radioAnswer2);
        group.add(radioAnswer3);
        group.add(radioAnswer4);

When the method is called it gives a NullPointerException at the line:

if (group.getSelection() != null) {

I don't know what I am doing wrong. Thanks in advance.


Solution

  • Quite possibly youre shadowing the group variable. Try replacing

    final ButtonGroup group = new ButtonGroup();
    

    with

    group = new ButtonGroup();