2017-11-29 22 views
1

JPanelJRadioButton을 사용하여 Java에서 "퀴즈"를 설정해야합니다.Java - radioButtons 및 JPanel에서 IsSelected 함수 사용

내 코드는 파일의 텍스트를 읽고 라디오 버튼, 버튼 그룹 및 패널과 함께 패널에 배치하는 것으로 시작됩니다. 여태까지는 그런대로 잘됐다.

그러나 사용자로부터 데이터를 수집하여 올바른 답과 비교해야 할 때 제 문제가 시작됩니다.

나는 질문, 답변 및 읽기 (패널에 주 및 디스플레이 제외) 클래스가 있습니다.

내 생각에 사용자가 submit 버튼을 클릭하면 코드 별이 퀴즈를 확인합니다. 그러나 열린 창에서 클릭하면 아무 일도 일어나지 않습니다.

비교를 위해 ArrayList에 데이터를 수집합니다.

checkQuiz 메서드는 사용자가 퀴즈를 제출 한 후에 호출해야합니다. 선택한 텍스트와 라디오 버튼을 비교합니다. 이 프로그램은 사용자가 "제출"버튼을 클릭 할 때까지 "실행 중"으로되어 있지만, 발생하지 않는다고 나는 믿는다.

코드에서 ActionListener을 사용하려했지만 사용자가 선택한 데이터를 사용중인 데이터와 비교할 수 없었습니다.

많은 코드에 대해 사과드립니다. 나는 mcve 질문을 올리려고했다. 필자가 아는 한 코드는 컴파일 가능하지만 더 이상 선을 무시할 수는 없다.

도움을 주셔서 감사합니다. 코드는 다음과 같습니다.

import javax.swing.JFrame; 

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

클래스 홈페이지 :

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

Clsas 질문 :

을 서브 클래스가 사용하는 App

클래스 DisplayOnPanel는 프레임을 생성

클래스 읽기 - 파일에서 읽고 그 결과를 패널에 표시합니다. 또한 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; 
     } 
    } 

} 

클래스 응답

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

} 

편집 - 내 작업 코드를 기록했다.

+0

를 사용합니다. 또한'DisplayOnPanel'에서 생성 한'frame' 객체는 아무데도 사용되지 않으므로 아무 쓸모가 없습니다. – Praveen

+0

EventListener의 문제점은 CheckQuiz 메소드와 비교하려고하기 때문에 nullPointerException이 발생한다는 것입니다. 어떻게 사용할 수 있습니까? 고맙습니다! – Alan

+0

EvenListener로 작업하려고 시도했습니다. 배열에서 작동하는 다른 메서드를 호출 할 수 없다는 것을 알았습니다. 널 예외가 항상 발생합니다. – Alan

답변

2

나는) 당신은 그것을 얻기 전에 조치 명령을 설정해야

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 메소드는 현재 사용중인 논리로 대부분 호출되지 않습니다. 따라서 나는 당신의 코드에서 어떤`EventListener`을 찾을 수없는 대신 whileActionListener 인터페이스,

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

감사합니다 !!! "setActionCommand"는 "Regular"ActionListener가 수행하지 않는 작업을 무엇입니까? – Alan

+1

'setActionCommand'는 액션 명령을'String' 형식으로 설정합니다.이 명령은'ActionListener'에서'ActionEvent'를 수행하는 동안 수행 할 동작을 식별하는 데 도움이됩니다. – Praveen