Java中的GUI窗口未能完全展示我的代码。

huangapple 未分类评论47阅读模式
英文:

Gui window in java does not fully show off my code

问题

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Practice implements ActionListener{
	
	String[] questions = {...}; // Your array of questions
	String[][] options = {...}; // Your array of options
	char[] answers = {...};     // Your array of answers
	
	// Other variables and GUI components

	public Practice() {
		// Your GUI initialization and setup code
	}

	public void nextScreen() {
		// Code to transition to the quiz screen
	}

	public void nextQuestion() {
		// Code to display the next question
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// Code to handle button clicks and user interaction
	}

	public void displayAnswer() {
		// Code to display the correct answer and handle transitions
	}

	public void results() {
		// Code to display quiz results
	}
	
	// Main method or other entry point for your program
}

Please note that I've only provided a summary of your code with placeholders for parts that are repetitive or not directly related to the core functionality. You should integrate this summary into your existing codebase and adapt it to match the structure and logic of your program.

英文:

I wrote this gui based code for a trivia, where it shows the first page where you can click start button to start the quiz. It worked, however, when it goes to the actual quiz window, it only shows few questions instead of showing all 15 and displays the result very quickly.. I wasn't able to find out what's wrong, though I'm assuming it is because of the public class actionListener. Although, I don't have an idea to fix it out. I would appreciate if someone gives some help..

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;



public class Practice implements ActionListener{
	
	
	String[] questions = 	{
								"Select the official name of the coronavirus.",
								"When did the corona virus first ecountered?",
								"What is the percentage of people recovering from the coronavirus?",
								"Which below is NOT the symptom of coronavirus?",
								"Which part of the human body does the    coronavirus attach itself to?",
								"How many hour can the coronavirus survive on plastic and stainless steel surfaces?",
								"Whihc human organs in the body does the coronavirus attack?",
								"How large is the coronavirus?",
								"Which is a safe distance to stay apart from people? ",
								"Who has the highest risk of getting infected by coronvirus?",
								"When should face masks be worn?",
								"Which is more effective for removing the coronavirus from your hands?",
								"Which industry includes workers with increased exposure-risk?",
								"What is the period of quartine?",
								"What is the name of the city where coronavirus    was first detected?"
								
							};
	String[][] options = 	{
								{"COVID-19","Sars-CoV-2","Zaire ebolavirus","Influenza"},
								{"2018","2020","2017","2019"},
								{"63%","71%","80%","76%"},
								{"Fever","Blurred vision","Dry Cough","Nasal Congestion"},
								{"Red Blood Cells", "Antigens", "White Blood Cells", "Ace-2 recpetors in the airways"},
								{"4-8 hours", "72 hours and more", "45-60 hours", "90 hours and more" },
								{"Liver", "Lungs", "Heart", "Kidney"},
								{"8000 billionths of metre in diameter", "800 billionths of metre in diameter","80 billionths of metre in diameter","8 billionths of metre in diameter"},
								{"3 feet(1 meter)", "2 feet(60 cm)", "1 foot (30cm)", "4.2 feet(1.3 meter)"},
								{"Children", "Pregnant Women", "People over 60 years of age", "30-40 years agr of men"},
								{"Public Transport", "Confined or Crowed spaces", "Small restaurants or shops", "All of the above"},
								{"Soap and water", "Alcohol-based hand sanitiser","Detergent", "Face cleanser"},
								{"Health care", "Airline operations", "Waste management", "All of the above"},
								{"21 days","7 days", "14 days", "6 days"},
								{"Wuhan", "Hubei", "Hunan","Shanghai"}
							};
	char[] answers = 		{
								'A',
								'D',
								'C',
								'B',
								'D',
								'B',
								'B',
								'C',
								'A',
								'C',
								'D',
								'A',
								'D',
								'B',
								'A'
							};
	
	char guess;
	char answer;
	int index;
	int correct_guesses =0;
	int total_questions = questions.length;
	int result;
	int seconds=15;
	
	JFrame frame = new JFrame();
	
	JTextField textName = new JTextField();
	JTextArea subtitle = new JTextArea();
	JButton startButton = new JButton();
	
	JTextField textfield = new JTextField();
	JTextArea textarea = new JTextArea();
	JButton buttonA = new JButton();
	JButton buttonB = new JButton();
	JButton buttonC = new JButton();
	JButton buttonD = new JButton();
	JLabel answer_labelA = new JLabel();
	JLabel answer_labelB = new JLabel();
	JLabel answer_labelC = new JLabel();
	JLabel answer_labelD = new JLabel();
	JLabel time_label = new JLabel();
	JLabel seconds_left = new JLabel();
	JTextField number_right = new JTextField();
	JTextField percentage = new JTextField();
	
	Timer timer = new Timer(1500, new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			seconds--;
			seconds_left.setText(String.valueOf(seconds));
			if(seconds<=0) {
				displayAnswer();
			}
			}
		});
	
public Practice() {
	
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(700,700);
		frame.getContentPane().setBackground(new Color(204,229,255));
		frame.setLayout(null);
		frame.setResizable(false);
		
		textName.setBounds(100, 100, 500, 170);
		textName.setBackground(new Color(153, 204, 255));
		textName.setForeground(new Color(0,76,153));
		textName.setFont(new Font("PT Serif",Font.BOLD,85));
		textName.setBorder(BorderFactory.createBevelBorder(2));
		textName.setHorizontalAlignment(JTextField.CENTER);
		textName.setText("Trivia!");
		textName.setEditable(false);
		
		
		
		
		startButton.setFont(new Font("Sans Serif", Font.PLAIN,25));
		startButton.setBounds(225, 440, 250, 100);
		startButton.setBackground(new Color(153, 204, 255));
		startButton.setFont(new Font("PT Serif",Font.BOLD,30));
		startButton.setText("START");
		startButton.addActionListener(this);

	
		frame.add(startButton);
		
		frame.add(textName);
		frame.setVisible(true);
	
}
public void nextScreen() {	
	
		textName.setVisible(false);
		startButton.setVisible(false);
		subtitle.setVisible(false);
	
		textfield.setBounds(0,0,700,70);
		textfield.setBackground(new Color(153, 204, 255));
		textfield.setForeground(new Color(0,25,51));
		textfield.setFont(new Font("PT Serif",Font.BOLD,33));
		textfield.setBorder(BorderFactory.createBevelBorder(0));
		textfield.setHorizontalAlignment(JTextField.CENTER);
		textfield.setEditable(false);
		
		textarea.setBounds(0,70,700,90);
		textarea.setLineWrap(true);
		textarea.setWrapStyleWord(true);
		textarea.setBackground(new Color(204,229,255));
		textarea.setForeground(new Color(0,25,51));
		textarea.setFont(new Font("PT Serif",Font.PLAIN,30));
		textarea.setLocation(16, 84);
		textarea.setEditable(false);
		
		buttonA.setBounds(50,200,50,50);
		buttonA.setFont(new Font("PT Serif",Font.BOLD,33));
		buttonA.setFocusable(false);
		buttonA.addActionListener(this);
		buttonA.setText("A");
		
		buttonB.setBounds(50,300,50,50);
		buttonB.setFont(new Font("PT Serif",Font.BOLD,33));
		buttonB.setFocusable(false);
		buttonB.addActionListener(this);
		buttonB.setText("B");
		
		buttonC.setBounds(50,400,50,50);
		buttonC.setFont(new Font("PT Serif",Font.BOLD,33));
		buttonC.setFocusable(false);
		buttonC.addActionListener(this);
		buttonC.setText("C");
		
		buttonD.setBounds(50,500,50,50);
		buttonD.setFont(new Font("PT Serif",Font.BOLD,33));
		buttonD.setFocusable(false);
		buttonD.addActionListener(this);
		buttonD.setText("D");
		
		answer_labelA.setBounds(130,175,500,100);
		answer_labelA.setBackground(new Color(50,50,50));
		answer_labelA.setForeground(new Color(0,25,51));
		answer_labelA.setFont(new Font("PT Serif",Font.PLAIN,26));
		
		answer_labelB.setBounds(130,275,500,100);
		answer_labelB.setBackground(new Color(50,50,50));
		answer_labelB.setForeground(new Color(0,25,51));
		answer_labelB.setFont(new Font("PT Serif",Font.PLAIN,26));
		
		answer_labelC.setBounds(130,375,500,100);
		answer_labelC.setBackground(new Color(50,50,50));
		answer_labelC.setForeground(new Color(0,25,51));
		answer_labelC.setFont(new Font("PT Serif",Font.PLAIN,26));
		
		answer_labelD.setBounds(130,475,500,100);
		answer_labelD.setBackground(new Color(204,229,255));
		answer_labelD.setForeground(new Color(0,25,51));
		answer_labelD.setFont(new Font("PT Serif",Font.PLAIN,26));
		
		seconds_left.setBounds(150,575,100,70);
		seconds_left.setBackground(new Color(204,229,255));
		seconds_left.setForeground(new Color(102, 102, 255));
		seconds_left.setFont(new Font("PT Serif",Font.PLAIN,37));
		seconds_left.setOpaque(true);
		seconds_left.setHorizontalAlignment(JTextField.CENTER);
		seconds_left.setText(String.valueOf(seconds));
		
		time_label.setBounds(50,575,100,70);
		time_label.setBackground(new Color(204,229,255));
		time_label.setForeground(new Color(102, 102, 255));
		time_label.setFont(new Font("PT Serif",Font.PLAIN,35));
		time_label.setHorizontalAlignment(JTextField.CENTER);
		time_label.setText("Timer");
		
		number_right.setBounds(225,225,200,100);
		number_right.setBackground(new Color(153,204,255));
		number_right.setForeground(new Color(0, 102, 204));
		number_right.setFont(new Font("PT Serif",Font.BOLD,50));
		number_right.setBorder(BorderFactory.createBevelBorder(1));
		number_right.setHorizontalAlignment(JTextField.CENTER);
		number_right.setEditable(false);
		
		percentage.setBounds(225,325,200,100);
		percentage.setBackground(new Color(153,204,255));
		percentage.setForeground(new Color(0,102,204));
		percentage.setFont(new Font("PT Serif",Font.BOLD,50));
		percentage.setBorder(BorderFactory.createBevelBorder(1));
		percentage.setHorizontalAlignment(JTextField.CENTER);
		percentage.setEditable(false);
		
		frame.add(time_label);
		frame.add(seconds_left);
		frame.add(answer_labelA);
		frame.add(answer_labelB);
		frame.add(answer_labelC);
		frame.add(answer_labelD);
		frame.add(buttonA);
		frame.add(buttonB);
		frame.add(buttonC);
		frame.add(buttonD);
		frame.add(textarea);
		frame.add(textfield);
		frame.setVisible(true);
		
		nextQuestion();
	}

	public void nextQuestion() {
		
		if(index>=total_questions) {
			results();
		}
		else {
			textfield.setText("Question "+(index+1));
			textarea.setText(questions[index]);
			answer_labelA.setText(options[index][0]);
			answer_labelB.setText(options[index][1]);
			answer_labelC.setText(options[index][2]);
			answer_labelD.setText(options[index][3]);
			timer.start();
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		
			nextScreen();
		
			buttonA.setEnabled(false);
			buttonB.setEnabled(false);
			buttonC.setEnabled(false);
			buttonD.setEnabled(false);
			
			if(e.getSource()==buttonA) {
				answer= 'A';
				if(answer == answers[index]) {
					correct_guesses++;
				}
			}
			if(e.getSource()==buttonB) {
				answer= 'B';
				if(answer == answers[index]) {
					correct_guesses++;
				}
			}
			if(e.getSource()==buttonC) {
				answer= 'C';
				if(answer == answers[index]) {
					correct_guesses++;
				}
			}
			if(e.getSource()==buttonD) {
				answer= 'D';
				if(answer == answers[index]) {
					correct_guesses++;
				}
			}
			displayAnswer();
	}
	public void displayAnswer() {
		
		timer.stop();
		
		buttonA.setEnabled(false);
		buttonB.setEnabled(false);
		buttonC.setEnabled(false);
		buttonD.setEnabled(false);
		
		if(answers[index] != 'A')
			answer_labelA.setForeground(new Color(255, 0, 0));
		if(answers[index] != 'B')
			answer_labelB.setForeground(new Color(255, 0, 0));
		if(answers[index] != 'C')
			answer_labelC.setForeground(new Color(255, 0, 0));
		if(answers[index] != 'D')
			answer_labelD.setForeground(new Color(255, 0, 0));
		
		Timer pause = new Timer(2000, new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				answer_labelA.setForeground(new Color(0,25,51));
				answer_labelB.setForeground(new Color(0,25,51));
				answer_labelC.setForeground(new Color(0,25,51));
				answer_labelD.setForeground(new Color(0,25,51));
				
				answer = ' ';
				seconds=15;
				seconds_left.setText(String.valueOf(seconds));
				buttonA.setEnabled(true);
				buttonB.setEnabled(true);
				buttonC.setEnabled(true);
				buttonD.setEnabled(true);
				index++;
				nextQuestion();
			}
		});
		pause.setRepeats(false);
		pause.start();
	}
	public void results(){
		
		buttonA.setEnabled(false);
		buttonB.setEnabled(false);
		buttonC.setEnabled(false);
		buttonD.setEnabled(false);
		
		result = (int)((correct_guesses/(double)total_questions)*100);
		
		textfield.setText("RESULTS!");
		textarea.setText("");
		answer_labelA.setText("");
		answer_labelB.setText("");
		answer_labelC.setText("");
		answer_labelD.setText("");
		
		number_right.setText("("+correct_guesses+"/"+total_questions+")");
		percentage.setText(result+"%");
		
		frame.add(number_right);
		frame.add(percentage);
		
	}
}

答案1

得分: 0

我做了一些更改

  1. 框架上只显示一个问题,这样用户只能专注于这个问题,并且只有在用户给出答案或问题超时(每个问题5秒)后才能继续下一个问题。

  2. 我将所有的问题和答案移到了一个文本文件中,该文件必须放在与其他类相同的包中。这样可以很容易地按指定格式添加新的问题。

  3. 去除了对 setBounds() 的使用,将该工作留给了布局管理器,然后使用 frame.pack() 让框架自己决定大小。

quiz.txt

问题=选择冠状病毒的官方名称。
选项=COVID-19,Sars-CoV-2,Zaire ebolavirus,Influenza
答案=A

问题=冠状病毒首次遇到是什么时候?
选项=2018,2020,2017,2019
答案=D

问题=从冠状病毒中恢复的人的百分比是多少?
选项=63%,71%,80%,76%
答案=C

问题=以下哪项不是冠状病毒的症状?
选项=发热,视力模糊,干咳,鼻塞
答案=B

问题=冠状病毒附着在人体的哪个部位?
选项=红细胞,抗原,白细胞,空气道中的Ace-2受体
答案=D

问题=冠状病毒在塑料和不锈钢表面可以存活多少小时?
选项=4-8小时,72小时及以上,45-60小时,90小时及以上
答案=B

问题=冠状病毒会攻击人体的哪些器官?
选项=肝脏,肺部,心脏,肾脏
答案=B

问题=冠状病毒有多大?
选项=直径为8000亿分之一米,直径为800亿分之一米,直径为80亿分之一米,直径为8亿分之一米
答案=C

问题=与人保持安全距离的距离是多少?
选项=3英尺(1米),2英尺(60厘米),1英尺(30厘米),4.2英尺(1.3米)
答案=A

问题=哪些人感染冠状病毒的风险最高?
选项=儿童,孕妇,60岁以上的人,30-40岁的男性
答案=C

问题=何时应该佩戴口罩?
选项=公共交通工具,封闭或拥挤的空间,小型餐馆或商店,以上所有
答案=D

问题=哪种方法更有效地清洁双手上的冠状病毒?
选项=肥皂和水,酒精洗手液,洗涤剂,面部清洁剂
答案=A

问题=哪个行业的工人暴露风险增加?
选项=医疗保健,航空公司运营,废物管理,以上所有
答案=D

问题=隔离期是多久?
选项=21天,7天,14天,6天
答案=B

问题=冠状病毒首次被检测出的城市是哪里?
选项=武汉,湖北,湖南,上海
答案=A

QuizLoader.java

final class QuizLoader 
{
 static String question;
 static List<String> options;
 static char answer;
 
 static Question loadQuiz()
 {
  try
  {
   List<Question> questions=new ArrayList();

   Files.readAllLines(Paths.get(QuizLoader.class.getResource("quiz.txt").toURI()))
        .stream()
        .map(line->line.trim())
        .filter(line->!line.isBlank() && !line.isEmpty())
        .forEach(line->
        {
         String lineInfo[]=line.trim().split("=");
         
         switch(lineInfo[0])
         {
          case "Question":question=lineInfo[1];
          break;
          case "Options":options=Arrays.asList(lineInfo[1].split(","));
          break;
          default:questions.add(new Question(question,options,lineInfo[1].charAt(0)));
         }
        });

   int size=questions.size();
   for(int i=0;i<size-1;i++)
   {
    Question
    current=questions.get(i),
    next=questions.get(i+1);
    
    current.nextQuestion=next;
   }
   
   return questions.get(0);
  }
  catch(IOException | URISyntaxException ex)
  {
   JOptionPane.showMessageDialog(null,"无法加载测验 "+ex.getMessage());
   
   System.exit(0);
  }
  
  return null;
 }

 static final class Question
 {
  public final String question;
  public final HashMap<Character,String> options=new HashMap();
  public final char answer;
  
  public Question nextQuestion;
  
  public Question(String question,List<String> options,char answer)
  {
   this.question=question;
   
   int size=options.size();
   for(int i=0;i<size;i++){this.options.put((char)(i+65),options.get(i));}
   
   this.answer=Character.toUpperCase(answer);
  }
  
  public int getAnswer(){return (int)((answer)-65);}
  public boolean isCorrect(int finalAnswer){return (char)(finalAnswer+65)==answer;}
 }
}

Questionpanel.java

final class QuestionPanel extends JPanel implements ActionListener


<details>
<summary>英文:</summary>


I made a few changes

1)Only one question shows up on the frame that way the user can focus only on that question and can progress to the next only when either he gives his answer or the question times out[5 sceonds per question]

2)I have moved all the Q/A to an text file which must be placed in the same package as the other classes. That way new question&#39;s can be added easily in the specified format

3)Removed the use of `setBounds()` and left that job to [layout managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) and then let the frame decide it&#39;s own size using `frame.pack()`

**quiz.txt**

    Question=Select the official name of the coronavirus.
    Options=COVID-19,Sars-CoV-2,Zaire ebolavirus,Influenza
    Answer=A
    
    Question=When did the corona virus first ecountered?
    Options=2018,2020,2017,2019
    Answer=D
    
    Question=What is the percentage of people recovering from the coronavirus?
    Options=63%,71%,80%,76%
    Answer=C
    
    Question=Which below is NOT the symptom of coronavirus?
    Options=Fever,Blurred vision,Dry Cough,Nasal Congestion
    Answer=B
    
    Question=Which part of the human body does the    coronavirus attach itself to?
    Options=Red Blood Cells, Antigens, White Blood Cells, Ace-2 recpetors in the airways
    Answer=D
    
    Question=How many hour can the coronavirus survive on plastic and stainless steel surfaces?
    Options=4-8 hours, 72 hours and more, 45-60 hours, 90 hours and more
    Answer=B
    
    Question=Which human organs in the body does the coronavirus attack?
    Options=Liver, Lungs, Heart, Kidney
    Answer=B
    
    Question=How large is the coronavirus?
    Options=8000 billionths of metre in diameter, 800 billionths of metre in diameter,80 billionths of metre in diameter,8 billionths of metre in diameter
    Answer=C
    
    Question=Which is a safe distance to stay apart from people?
    Options=3 feet(1 meter), 2 feet(60 cm), 1 foot (30cm), 4.2 feet(1.3 meter)
    Answer=A
    
    Question=Who has the highest risk of getting infected by coronvirus?
    Options=Children, Pregnant Women, People over 60 years of age, 30-40 years agr of men
    Answer=C
    
    Question=When should face masks be worn?
    Options=Public Transport, Confined or Crowed spaces, Small restaurants or shops, All of the above
    Answer=D
    
    Question=Which is more effective for removing the coronavirus from your hands?
    Options=Soap and water, Alcohol-based hand sanitiser,Detergent, Face cleanser
    Answer=A
    
    Question=Which industry includes workers with increased exposure-risk?
    Options=Health care, Airline operations, Waste management, All of the above
    Answer=D
    
    Question=What is the period of quartine?
    Options=21 days,7 days, 14 days, 6 days
    Answer=B
    
    Question=What is the name of the city where coronavirus  was first detected?
    Options=Wuhan, Hubei, Hunan,Shanghai
    Answer=A

**QuizLoader.java**

    final class QuizLoader 
    {
     static String question;
     static List&lt;String&gt; options;
     static char answer;
     
     
     static Question loadQuiz()
     {
      try
      {
       List&lt;Question&gt; questions=new ArrayList();
    
       Files.readAllLines(Paths.get(QuizLoader.class.getResource(&quot;quiz.txt&quot;).toURI()))
            .stream()
            .map(line-&gt;line.trim())
            .filter(line-&gt;!line.isBlank() &amp;&amp; !line.isEmpty())
            .forEach(line-&gt;
            {
             String lineInfo[]=line.trim().split(&quot;=&quot;);
             
             switch(lineInfo[0])
             {
              case &quot;Question&quot;:question=lineInfo[1];
              break;
              case &quot;Options&quot;:options=Arrays.asList(lineInfo[1].split(&quot;,&quot;));
              break;
              default:questions.add(new Question(question,options,lineInfo[1].charAt(0)));
             }
            });
    
       int size=questions.size();
       for(int i=0;i&lt;size-1;i++)
       {
        Question
        current=questions.get(i),
        next=questions.get(i+1);
        
        current.nextQuestion=next;
       }
       
       return questions.get(0);
      }
      catch(IOException | URISyntaxException ex)
      {
       JOptionPane.showMessageDialog(null,&quot;Unable To Load Quiz &quot;+ex.getMessage());
       
       System.exit(0);
      }
      
      return null;
     }
    
     static final class Question
     {
      public final String question;
      public final HashMap&lt;Character,String&gt; options=new HashMap();
      public final char answer;
      
      public Question nextQuestion;
      //ASCII Value OF &#39;A&#39;=65,B=&#39;66&#39; so on
      public Question(String question,List&lt;String&gt; options,char answer)
      {
       this.question=question;
       
       int size=options.size();
       for(int i=0;i&lt;size;i++){this.options.put((char)(i+65),options.get(i));}
       
       this.answer=Character.toUpperCase(answer);
      }
      
      public int getAnswer(){return (int)((answer)-65);}
      public boolean isCorrect(int finalAnswer){return (char)(finalAnswer+65)==answer;}
     }
    }

**Questionpanel.java**

    final class QuestionPanel extends JPanel implements ActionListener
    {
     private final InfoPanel infoPanel;
     private final OptionsPanel options;
     private final ResponsePanel response;
     
     private final Question thisQuestion;
     private int nextQuestionIn=3;
     private final Timer timer=new Timer(1000,this);
     
     QuestionPanel(QuizPanel mainPanel,Question question)
     {
      super(new BorderLayout(0,30));
      
      this.thisQuestion=question;
      
      add(infoPanel=new InfoPanel(question.question),BorderLayout.NORTH);
      
      add(options=new OptionsPanel(question.options,question.answer),BorderLayout.CENTER);
      
      add(response=new ResponsePanel(mainPanel),BorderLayout.SOUTH);
      
      setBackground(Color.white);
      
      timer.start();
     }
     
     @Override
     public void actionPerformed(ActionEvent e)
     {
      boolean timeUp=infoPanel.decreaseTimeLeft();
      
      if(timeUp)
      {
       options.highLightAnswer(null);
       
       nextQuestionIn--;
       
       if(nextQuestionIn==0)
       {
        timer.stop();
        
        response.actions[2].doClick();
       }
      }
     }
     
     private final class InfoPanel extends JPanel
     {
      private final JLabel timeLeft; 
      
      private InfoPanel(String questionTxt)
      {
       super(new BorderLayout());
       
       add(create(questionTxt,JLabel.LEFT),BorderLayout.WEST);
       
       add(timeLeft=create(&quot;5 Seconds Left&quot;,JLabel.RIGHT),BorderLayout.EAST);
       
       setOpaque(false);
      }
      
      private JLabel create(String text,int textPosition)
      {
       JLabel label=new JLabel(text);
       
       label.setHorizontalAlignment(textPosition);
       
       return label;
      }
      
      private boolean decreaseTimeLeft()
      {
       int timeLeftInt=Integer.parseInt(&quot;&quot;+timeLeft.getText().charAt(0));
       
       if(timeLeftInt==0){return true;}
       
       timeLeftInt--;
       
       timeLeft.setText(timeLeftInt+&quot; Seconds Left&quot;);
       
       if(timeLeftInt&lt;3){timeLeft.setForeground(Color.red);}
       
       return false;
      }
     }
     
     private final class OptionsPanel extends JPanel
     {
      private final char rightAnswer;
      private final ButtonGroup buttonGroup=new ButtonGroup();
      
      OptionsPanel(HashMap&lt;Character,String&gt; optionsMap,char rightAnswer)
      {
       super(new GridLayout(4,1,0,20));
       
       setOpaque(false);
       
       JRadioButton[] options=new JRadioButton[optionsMap.size()];
       
       optionsMap.entrySet().forEach(entry-&gt;
       {
        int index=((int)(entry.getKey()))-65;
        
        options[index]=new JRadioButton();
        
        options[index].setActionCommand(&quot;&quot;+entry.getKey());
        
        options[index].setText(entry.getValue());
       
        options[index].setOpaque(false);
        
        buttonGroup.add(options[index]);
        
        add(options[index]);
       });
       
       this.rightAnswer=rightAnswer;
      
       setPreferredSize(new Dimension(200,150));
      }
      
      private void highLightAnswer(String selected)
      {
       Enumeration&lt;AbstractButton&gt; allOptions=buttonGroup.getElements();
       
       while(allOptions.hasMoreElements())
       {
        JRadioButton option=(JRadioButton)allOptions.nextElement();
          
        String action=option.getActionCommand();
        if(action.equals(&quot;&quot;+rightAnswer))
        {
         option.setSelected(true);
         
         option.setForeground(Color.green);
        }
        else if(selected!=null &amp;&amp; action.equals(selected) &amp;&amp; !selected.equals(&quot;&quot;+rightAnswer)){option.setForeground(Color.red);}
        
        option.setEnabled((selected!=null &amp;&amp; action.equals(selected)) || action.equals(&quot;&quot;+rightAnswer));
       }
      }
      
      private boolean verifyAnswer()
      {
       String selected=buttonGroup.getSelection().getActionCommand();
       
       timer.stop();
       
       JOptionPane.showMessageDialog(null,selected.equals(&quot;&quot;+rightAnswer)?&quot;Correct&quot;:&quot;Wrong Right Answer Is &quot;+rightAnswer);
       
       highLightAnswer(selected);
       
       return selected.equals(&quot;&quot;+rightAnswer);
      }
     }
     
     private final class ResponsePanel extends JPanel implements ActionListener
     {
      private final QuizPanel quizPanel;
      private boolean response;
      private final JButton actions[]=new JButton[3];
      
      private ResponsePanel(QuizPanel quizPanel)
      {
       super(new FlowLayout(FlowLayout.TRAILING,50,0));
       
       setOpaque(false);
       
       this.quizPanel=quizPanel;
       
       for(int i=0;i&lt;3;i++)
       {
        actions[i]=new JButton();
        
        switch(i)
        {
         case 0:actions[i].setText(&quot;I Give Up&quot;);
         break;
         case 1:actions[i].setText(&quot;Confirm&quot;);
         break;
         default:actions[i].setText(&quot;Next Question&quot;);
        }
        
        actions[i].setActionCommand(&quot;&quot;+i);
        
        actions[i].addActionListener(ResponsePanel.this);
        
        actions[i].setPreferredSize(new Dimension(150,30));
        
        add(actions[i]);
       }
      }
      
      @Override
      public void actionPerformed(ActionEvent e)
      {
       String action=e.getActionCommand();
       
       if(action.equals(&quot;0&quot;) || action.equals(&quot;1&quot;))
       {
        timer.stop();
        switch(action)
        {
         case &quot;0&quot;:options.highLightAnswer(null);
         break;
         default:response=options.verifyAnswer();
        } 
        for(int i=0;i&lt;2;i++){actions[i].setEnabled(false);}
       }
       else
       {
        timer.stop();
        
        quizPanel.setQuestion(response,thisQuestion.nextQuestion);
       }
      }
     }
    }

**QuizPanel.java**

    final class QuizPanel extends JPanel
    {
     private final JFrame mainFrame;
     private final Question firstQuestion;
     private int score=0;
     
     QuizPanel(JFrame mainFrame)
     {
      super(new BorderLayout());
      
      this.mainFrame=mainFrame;
      
      this.firstQuestion=QuizLoader.loadQuiz();
      
      add(new QuestionPanel(QuizPanel.this,firstQuestion));
     }
     
     void setQuestion(boolean addScore,Question question)
     {
      if(addScore){score++;}
       
      removeAll();
    
      add(question!=null?new QuestionPanel(this,question):new TryAgainPanel());
    
      revalidate();
    
      repaint();
      
      mainFrame.pack();
     }
     
     private final class TryAgainPanel extends JPanel implements ActionListener
     {
      private TryAgainPanel()
      {
       super(new BorderLayout(0,50));
       
       JLabel msg=new JLabel(&quot;Your Score Is &quot;+score);
       
       msg.setHorizontalAlignment(JLabel.CENTER);
       
       msg.setPreferredSize(new Dimension(250,50));
       
       add(msg,BorderLayout.NORTH);
       
       JButton tryAgain=new JButton(&quot;Try Again?&quot;);
       
       tryAgain.addActionListener(TryAgainPanel.this);
       
       tryAgain.setPreferredSize(new Dimension(100,30));
       
       add(tryAgain,BorderLayout.CENTER);
      }
      
      @Override
      public void actionPerformed(ActionEvent e)
      {
       score=0;
       
       setQuestion(false,firstQuestion);
      }
     }
    }

**Main.java**

    public class Main 
    {
     public static void main(String[] args)
     {
      JFrame main=new JFrame(&quot;&quot;);
      
      main.setContentPane(new QuizPanel(main));
      
      main.pack();
      
      main.setResizable(false);
      
      main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
      main.setVisible(true);
     }
    }

If you would like all the questions to show up on the same page you can create an scroll pane containing an JPanel with box layout along Y axis and add all the QuestionPanel&#39;s there but that would take up a lot of memory in my openion but see what work&#39;s for you 


</details>



huangapple
  • 本文由 发表于 2020年7月27日 14:43:42
  • 转载请务必保留本文链接:https://java.coder-hub.com/63109970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定