JRadioButtonGroup:带有getSelection()。getActionCommand()的nullPointerException

时间:2019-12-12 16:09:22

标签: java swing jradiobutton buttongroup

正确遵循我的课程幻灯片和StackOverflow-answers中的所有说明,我继续获得相同的nullPointerException。它与JRadioButtons的ButtonGroup有关,我正尝试获取其选定值以在代码中进一步使用它。如您所见,我设置了actionCommand并按照我所看到的正确完成了所有操作。 在这里:

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);
            }
        }); 

字符串难度级别= diffLevelGroup.getSelection()。getActionCommand();当我将它们放在这些按钮的ActionListener中时,它可以正常工作(这是我尝试过的,并且可以工作,只是将其从这段代码中删除了),但是后来我无法从startButton-ActionListener访问它。 (所有其他参数,类和对象都是有效的东西,因此不必担心它们) 有人知道我该怎么做吗?

0 个答案:

没有答案