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.

有帮助吗?

解决方案

Quite possibly youre shadowing the group variable. Try replacing

final ButtonGroup group = new ButtonGroup();

with

group = new ButtonGroup();

其他提示

If the exception is indeed on this line

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

(and not in getSelection() itself),
then group is null there.

Make sure it's initialized first.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top