Java - 在 radioButtons 和 JPanel 中使用 IsSelected 函数

Java - using a IsSelected function in radioButtons and JPanel

我必须在 Java 中设置 "quiz",使用 JPanelJRadioButton

我的代码首先从文件中读取文本并将其放在面板上,其中包含单选按钮、按钮组和面板。到目前为止,还不错。

然而,当我必须从用户那里收集数据并将其与正确答案进行比较时,我的问题就开始了。

我有 class 个问题、答案和阅读(除了面板上的主要和显示)。

我的想法是,当用户单击 submit 按钮时,代码星号会检查以进行测验。但是,当我在 window 打开时单击它时没有任何反应。

我收集数据到ArrayList进行比较。

checkQuiz 方法应该在用户提交测验后调用。它将单选按钮选择的文本与答案进行比较。该程序应该是 "running",直到用户单击 "submit" 按钮,但我相信它不会发生。

我尝试在代码中使用 ActionListener,但我无法将用户的选择与我正在使用的数据进行比较。

对不起,代码太多了。我试图 post 一个 mcve 问题。 据我所知代码是可编译的,但我不能忽略更多行。

感谢您的帮助,代码如下。

Class DisplayOnPanel 创建一个 Frame 供 subclass 使用:

import javax.swing.JFrame;

public class DisplayOnPanel extends JFrame {
    JFrame frame = new JFrame();
    public DisplayOnPanel(){
        frame.setSize(500,500);
    }
}

Class 主要:

public class Main {
public static void main (String[]args){
      new Read();
    }
}

分类问题:

public class Question {
private String _question;
private String _option1;
private String _option2;
private String _option3;
private String _option4;
private int _qIndex=0;
public Question(String question, String option1, String option2, String option3,
                String option4){
    this._question = question;
    this._option1 = option1;
    this._option2 = option2;
    this._option3 = option3;
    this._option4 = option4;


}
public void set_qIndex(int index) {
    this._qIndex = index;
}

Class 读取 - 从文件读取,然后在面板上显示结果。它还用 Answers、Questions、ButtonGroups 和 JPanels 填充 ArrayLists。

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Read extends DisplayOnPanel {


protected ArrayList<Question> Questions = new ArrayList<>();
protected ArrayList<ButtonGroup> BG = new ArrayList<>();
protected ArrayList<JPanel> JP = new ArrayList<>();
protected ArrayList<Answer> Answers = new ArrayList<>();
protected int qNumber = 0, finalscore = 0;
private JLabel lblScore;
private JToggleButton Submit = new JToggleButton();
//constructor

public Read() {
    super();
    //a "label" in the file will indicate the final score
    final int NUMBER_OF_LABELS_ADDED_TO_FRAME = 1;
    int number_of_lines_in_the_file, final_score = 0;
    try {
        number_of_lines_in_the_file = read(Questions);
        addButtonsToFrame(Questions, number_of_lines_in_the_file +
                NUMBER_OF_LABELS_ADDED_TO_FRAME, BG, JP);
        Submit.setText("Submit Quiz"); //create a submit button
        JPanel SubmitPanel = new JPanel();
        SubmitPanel.setVisible(true);
        this.add(SubmitPanel);
        SubmitPanel.add(Submit);

Submit.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    for (int i = 0; i < BG.size(); i++) {
                        //handle cases of the user didn't complete the test
                        if (BG.get(i).getSelection()==null) {
                            JOptionPane.showMessageDialog(frame, "Exam not finished - Restart.");
                            i=BG.size()-1; //finish the loop
                            frame.setVisible(false);
                            dispose();
                            new Read();
                        }
                    }
                    checkQuiz(BG, Answers, ONE_QUESTION_GRADE); //check quiz
                    Submit.setEnabled(false); //can't redo quiz //
                    // unless "Restart" pressed


                }
            });            
//adding final score label
        lblScore = new JLabel("Your Final Score: " + finalscore);
        add(lblScore);
        pack();
        this.setVisible(true);
        while (!Submit.isSelected()) {
            if (Submit.isSelected()) {
                checkQuiz(BG, Answers);
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("couldn't open file");
    }
}
//the method reads from the file


//returns the number of lines (quesiton) in the file

public int read(ArrayList<Question> Questions) throws FileNotFoundException {
    int number_of_lines = 0;
    try {
        File f = new File("C:\Users\Assaf\Desktop\exam.txt");
        Scanner input = new Scanner(f);
        //read from file direcly into the constructor
        while (input.hasNext()) {
            Question q = new Question((input.nextLine())
                    , (input.nextLine()),
                    (input.nextLine()),
                    (input.nextLine()),
                    (input.nextLine()));
            //adding the question and the answers to an array
            Questions.add(q);
            number_of_lines++;
            q.set_qIndex(number_of_lines);
            Answers.add(new Answer(q));

        }
        input.close();
    } catch (FileNotFoundException nf) {
        System.out.println("couldn't open file");
    }
    //return number of lines in the file
    return number_of_lines;
}
public void addButtonsToFrame(ArrayList<Question> q, int number_of_lines,
                              ArrayList<ButtonGroup> BG, ArrayList<JPanel> JP) {
    int j = 0;
    for (int i = 0; i < q.size(); i++) {
        qNumber = i;
        BG.add(new ButtonGroup());
        JP.add(new JPanel());
        JP.get(i).setSize(499, 400);
        //creating buttons
JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
option1.setActionCommand(q.get(i).get_option1());
JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
option2.setActionCommand(q.get(i).get_option2());
JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
option3.setActionCommand(q.get(i).get_option3());
JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
option4.setActionCommand(q.get(i).get_option4());
        //adding to group buttons
        BG.get(j).add(option1);
        BG.get(j).add(option2);
        BG.get(j).add(option3);
        BG.get(j).add(option4);
        //adding the buttons to the panel
        JP.get(j).add(option1);
        JP.get(j).add(option2);
        JP.get(j).add(option3);
        JP.get(j).add(option4);
        //setting layout that matches our goal
        this.setLayout(new GridLayout(number_of_lines + 1, 1));
        //set title and border for each question
        JP.get(i).setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(), "question number " + qNumber + ": " + q.get(i).get_question()));
        //adding the panel to the frame
        this.add(JP.get(j));
        //BG.get(i).getSelection()
        JP.get(j).setVisible(true);
        j++;
    }
}
public void checkQuiz(ArrayList<ButtonGroup> BG, ArrayList<Answer> A) {
    ArrayList<String> Selections = new ArrayList<>();
    int CORRECT_ANSWER = 0;
    for (int i = 0; i < BG.size(); i++) {
        if (BG.get(i).getSelection().getActionCommand()
                .compareTo(A.get(i).get_answer()) == CORRECT_ANSWER) {
            finalscore = finalscore + 10;
        }
    }

}

Class 回答

public class Answer {
private String _question;
private String _answer;
private int _qIndex=0;

public Answer (Question q){
    this._answer = q.get_option1();
    this._question=q.get_question();
    this._qIndex=q.get_qIndex();

}

编辑 - post编辑了我的工作代码。

i)获取前需要先设置动作命令,

JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
option1.setActionCommand(q.get(i).get_option1());
JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
option2.setActionCommand(q.get(i).get_option2());
JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
option3.setActionCommand(q.get(i).get_option3());
JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
option4.setActionCommand(q.get(i).get_option4());

ii) 你还没有在checkQuiz方法的最后在你的标签中设置最终分数,
lblScore.setText("Your Final Score: " + finalscore);

iii) 不建议使用 while 循环。此外,checkQuiz 方法在大多数情况下不会被您使用的当前逻辑调用。因此使用 ActionListener 接口而不是 while,

Submit.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
         checkQuiz(BG, Answers);
    }
});