0

I am currently facing an issue with putting items from an array to JRadioButtons. I have the below code and when I try to add them to the JFrame it comes out with the following error.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot store to object array because "this.answersButtons" is null
public class AddAnswerFinal extends JFrame {
    JRadioButton[] answersButtons;
    ButtonGroup buttonGroup = new ButtonGroup();

    public AddAnswerFinal(String question, ArrayList<String> prevAnswers, Integer adminID, String first, String last) {
        ArrayList<String> answers = new ArrayList<>(prevAnswers);
        System.out.println(answers);
        for (Integer i = 0; i < answers.size(); i++) {
            answersButtons[i] = new JRadioButton(answers.get(i));
            buttonGroup.add(answersButtons[i]);
            this.add(answersButtons[i]);
        }

        this.setTitle("Quiz Application - Finalize Question");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(new Dimension(800, 500));
        this.setLocation(150, 150);
        this.setVisible(true);
    }
}

I also tried doing it where I used

this.add(buttonGroup)

But it came out with the following error Cannot resolve method 'add(javax.swing.ButtonGroup)'

IAmAndy
  • 121
  • 2
  • 12
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – maloomeister Apr 07 '21 at 14:49
  • 1
    You never initialize `answersButtons`. So in your `addAnswerFinal` method, the first thing you should do is `answersButtons = new JRadioButton[answers.size()]`. – maloomeister Apr 07 '21 at 14:51
  • 1
    You initialize each `JRadioButton` but not the array itself – Frakcool Apr 07 '21 at 14:51

1 Answers1

1

Array field JRadioButton[] answersButtons is not initialized.