我写了这个基于gui的代码,它显示了你可以点击开始按钮开始测验的第一页。然而,当它转到实际的测验窗口时,它只显示几个问题,而不是显示所有15个问题,并非常快地显示结果。我不能找出问题出在哪里,尽管我认为这是因为公共类actionListener。不过,我没有办法解决这个问题。如果有人能给我一些帮助,我将不胜感激..
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);
}
}发布于 2020-07-28 17:27:05
我做了一些改动
1)只有一个问题显示在框中,这样用户只能专注于该问题,并且只有当他给出答案或每个问题的问题时间为out5秒时,才能进入下一个问题
2)我已经将所有的Q/A都移到了一个文本文件中,该文件必须与其他类放在同一个包中。这样就可以很容易地以指定的格式添加新问题
3)删除了setBounds()的使用,将该工作留给了layout managers,然后使用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=AQuizLoader.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,"Unable To Load Quiz "+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;
//ASCII Value OF 'A'=65,B='66' so on
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
{
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("5 Seconds Left",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(""+timeLeft.getText().charAt(0));
if(timeLeftInt==0){return true;}
timeLeftInt--;
timeLeft.setText(timeLeftInt+" Seconds Left");
if(timeLeftInt<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<Character,String> optionsMap,char rightAnswer)
{
super(new GridLayout(4,1,0,20));
setOpaque(false);
JRadioButton[] options=new JRadioButton[optionsMap.size()];
optionsMap.entrySet().forEach(entry->
{
int index=((int)(entry.getKey()))-65;
options[index]=new JRadioButton();
options[index].setActionCommand(""+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<AbstractButton> allOptions=buttonGroup.getElements();
while(allOptions.hasMoreElements())
{
JRadioButton option=(JRadioButton)allOptions.nextElement();
String action=option.getActionCommand();
if(action.equals(""+rightAnswer))
{
option.setSelected(true);
option.setForeground(Color.green);
}
else if(selected!=null && action.equals(selected) && !selected.equals(""+rightAnswer)){option.setForeground(Color.red);}
option.setEnabled((selected!=null && action.equals(selected)) || action.equals(""+rightAnswer));
}
}
private boolean verifyAnswer()
{
String selected=buttonGroup.getSelection().getActionCommand();
timer.stop();
JOptionPane.showMessageDialog(null,selected.equals(""+rightAnswer)?"Correct":"Wrong Right Answer Is "+rightAnswer);
highLightAnswer(selected);
return selected.equals(""+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<3;i++)
{
actions[i]=new JButton();
switch(i)
{
case 0:actions[i].setText("I Give Up");
break;
case 1:actions[i].setText("Confirm");
break;
default:actions[i].setText("Next Question");
}
actions[i].setActionCommand(""+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("0") || action.equals("1"))
{
timer.stop();
switch(action)
{
case "0":options.highLightAnswer(null);
break;
default:response=options.verifyAnswer();
}
for(int i=0;i<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("Your Score Is "+score);
msg.setHorizontalAlignment(JLabel.CENTER);
msg.setPreferredSize(new Dimension(250,50));
add(msg,BorderLayout.NORTH);
JButton tryAgain=new JButton("Try Again?");
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("");
main.setContentPane(new QuizPanel(main));
main.pack();
main.setResizable(false);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
}
}如果您希望所有问题都显示在同一页上,您可以创建一个滚动窗格,其中包含一个沿Y轴具有框布局的JPanel,并在那里添加所有的QuestionPanel,但这将占用我打开的大量内存,但请看哪种方法适合您
https://stackoverflow.com/questions/63109970
复制相似问题