【问题标题】:Issue with JRadioButton and setting an Array [closed]JRadioButton 问题和设置数组[关闭]
【发布时间】:2021-07-03 09:53:12
【问题描述】:

我目前面临将数组中的项目放入 JRadioButtons 的问题。我有以下代码,当我尝试将它们添加到 JFrame 时,会出现以下错误。

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

我也试过在我用过的地方做

this.add(buttonGroup)

但出现以下错误Cannot resolve method 'add(javax.swing.ButtonGroup)'

【问题讨论】:

  • 你永远不会初始化answersButtons。所以在你的addAnswerFinal 方法中,你应该做的第一件事是answersButtons = new JRadioButton[answers.size()]
  • 你初始化每个 JRadioButton 但不是数组本身

标签: java arrays swing arraylist


【解决方案1】:

数组字段 JRadioButton[] answersButtons 未初始化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多