WilGos
WilGos

Reputation: 1

JRadioButtonGroup: nullPointerException with getSelection().getActionCommand()

Properly following all instructions from my course slides and StackOverflow-answers, I keep on getting the same nullPointerException. It's about a ButtonGroup of JRadioButtons of which I am trying to get the selected value to use it further in my code. As you can see, I set the actionCommand and did -as I see it- everything correctly. Here it is:

String[] diffLevels = {"A","B","C","D","E"};
    JRadioButton[] diffLevelButtons = new JRadioButton[diffLevels.length];
    JPanel diffLevButtonPanel = new JPanel();
    diffLevButtonPanel.setLayout(new GridLayout(1,5));
    ButtonGroup diffLevelGroup = new ButtonGroup();
    for (int i = 0; i < diffLevels.length; i++) {
        diffLevelButtons[i] = new JRadioButton(diffLevels[i]);
        diffLevelButtons[i].setActionCommand(diffLevels[i]);
        diffLevelGroup.add(diffLevelButtons[i]);
        diffLevButtonPanel.add(diffLevelButtons[i]);
    }
String difficultyLevel = diffLevelGroup.getSelection().getActionCommand();
JButton startButton = new JButton("Start game");
        Game myGame = new Game();
        startButton.addActionListener(new StartButtonListener(myGame) {
            @Override
            public void actionPerformed(ActionEvent e) {
                myGame.prepareGame(nbRows,nbColumns,diffLevel,playerMode,player1ChosenName,player2ChosenName);
                GameFrameMaker gameFrameMaker = new GameFrameMaker();
                gameFrameMaker.makeGameFrame(myGame.board);
            }
        }); 

String difficultyLevel = diffLevelGroup.getSelection().getActionCommand(); works when I put it inside an ActionListener for these buttons (that's what I've tried and it works, just left it out of this piece of code), but then I can't access it from the startButton-ActionListener. (All the other parameters, classes and objects are things that work, so don't worry about them) Anyone an idea how I could make this work?

Upvotes: 0

Views: 495

Answers (0)

Related Questions