无法在基于GUI的Java程序中添加标题页

huangapple go评论80阅读模式
英文:

Cannot add a title page in the GUI based program java

问题

请注意,因为你的代码比较长,我只能显示其中的部分。以下是你提供的代码的翻译:

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

public class TriviaOne implements ActionListener {

    // ... (省略了你的问题数组,选项数组,答案数组等等)

    char 猜测;
    char 答案;
    int 索引;
    int 正确猜测数 = 0;
    int 总问题数 = 问题.length;
    int 结果;
    int 秒数 = 15;

    JFrame 框架 = new JFrame();

    JTextField 文本字段 = new JTextField();
    JTextArea 文本区 = new JTextArea();
    JButton 按钮A = new JButton();
    JButton 按钮B = new JButton();
    JButton 按钮C = new JButton();
    JButton 按钮D = new JButton();
    JLabel 答案标签A = new JLabel();
    JLabel 答案标签B = new JLabel();
    JLabel 答案标签C = new JLabel();
    JLabel 答案标签D = new JLabel();
    JLabel 时间标签 = new JLabel();
    JLabel 剩余秒数 = new JLabel();
    JTextField 正确数 = new JTextField();
    JTextField 百分比 = new JTextField();

    Timer 计时器 = new Timer(1500, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            秒数--;
            剩余秒数.setText(String.valueOf(秒数));
            if (秒数 <= 0) {
                显示答案();
            }
        }
    });

    public TriviaOne() {
        // ... (省略了初始化框架和其他组件的部分)

        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() {
        // ... (省略了问题切换的部分)
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // ... (省略了按钮点击事件的部分)
    }

    public void displayAnswer() {
        // ... (省略了显示答案和切换问题的部分)
    }

    public void results() {
        // ... (省略了显示结果的部分)
    }
}

这是你提供的代码的翻译版本。如果你有进一步的问题或需要其他帮助,请随时询问。

英文:

While I was writing this code,I wanted to add the start page where you are able to click the start button to start the actual quiz. I had made the actual quiz structure, but while I was trying to make the start page, it didn't work well. When I combined it the start page did work and I was able to move on to the quiz part. However, the quiz did not worked properly as it did not show full 15 questions instead it only showed a few and straightly moved it to the result.

This is my code for the quiz and the below code is the code I came up with the start page. I don't know how to add this together. It would be really helpful if someone gives me some help.

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TriviaOne implements ActionListener{
//Questions that will be in the trivia 
String[] questions = 	{
&quot;Select the official name of the coronavirus.&quot;,
&quot;When did the corona virus first ecountered?&quot;,
&quot;What is the percentage of people recovering from the coronavirus?&quot;,
&quot;Which below is NOT the symptom of coronavirus?&quot;,
&quot;Which part of the human body does the    coronavirus attach itself to?&quot;,
&quot;How many hour can the coronavirus survive on plastic and stainless steel surfaces?&quot;,
&quot;Whihc human organs in the body does the coronavirus attack?&quot;,
&quot;How large is the coronavirus?&quot;,
&quot;Which is a safe distance to stay apart from people? &quot;,
&quot;Who has the highest risk of getting infected by coronvirus?&quot;,
&quot;When should face masks be worn?&quot;,
&quot;Which is more effective for removing the coronavirus from your hands?&quot;,
&quot;Which industry includes workers with increased exposure-risk?&quot;,
&quot;What is the period of quartine?&quot;,
&quot;What is the name of the city where coronavirus    was first detected?&quot;
};
//the 4 answer choices that leads the user to choose
String[][] options = 	{
{&quot;COVID-19&quot;,&quot;Sars-CoV-2&quot;,&quot;Zaire ebolavirus&quot;,&quot;Influenza&quot;},
{&quot;2018&quot;,&quot;2020&quot;,&quot;2017&quot;,&quot;2019&quot;},
{&quot;63%&quot;,&quot;71%&quot;,&quot;80%&quot;,&quot;76%&quot;},
{&quot;Fever&quot;,&quot;Blurred vision&quot;,&quot;Dry Cough&quot;,&quot;Nasal Congestion&quot;},
{&quot;Red Blood Cells&quot;, &quot;Antigens&quot;, &quot;White Blood Cells&quot;, &quot;Ace-2 recpetors in the airways&quot;},
{&quot;4-8 hours&quot;, &quot;72 hours and more&quot;, &quot;45-60 hours&quot;, &quot;90 hours and more&quot; },
{&quot;Liver&quot;, &quot;Lungs&quot;, &quot;Heart&quot;, &quot;Kidney&quot;},
{&quot;8000 billionths of metre in diameter&quot;, &quot;800 billionths of metre in diameter&quot;,&quot;80 billionths of metre in diameter&quot;,&quot;8 billionths of metre in diameter&quot;},
{&quot;3 feet(1 meter)&quot;, &quot;2 feet(60 cm)&quot;, &quot;1 foot (30cm)&quot;, &quot;4.2 feet(1.3 meter)&quot;},
{&quot;Children&quot;, &quot;Pregnant Women&quot;, &quot;People over 60 years of age&quot;, &quot;30-40 years agr of men&quot;},
{&quot;Public Transport&quot;, &quot;Confined or Crowed spaces&quot;, &quot;Small restaurants or shops&quot;, &quot;All of the above&quot;},
{&quot;Soap and water&quot;, &quot;Alcohol-based hand sanitiser&quot;,&quot;Detergent&quot;, &quot;Face cleanser&quot;},
{&quot;Health care&quot;, &quot;Airline operations&quot;, &quot;Waste management&quot;, &quot;All of the above&quot;},
{&quot;21 days&quot;,&quot;7 days&quot;, &quot;14 days&quot;, &quot;6 days&quot;},
{&quot;Wuhan&quot;, &quot;Hubei&quot;, &quot;Hunan&quot;,&quot;Shanghai&quot;}
};
//correct answers for the following questions
char[] answers = 		{
&#39;A&#39;,
&#39;D&#39;,
&#39;C&#39;,
&#39;B&#39;,
&#39;D&#39;,
&#39;B&#39;,
&#39;B&#39;,
&#39;C&#39;,
&#39;A&#39;,
&#39;C&#39;,
&#39;D&#39;,
&#39;A&#39;,
&#39;D&#39;,
&#39;C&#39;,
&#39;A&#39;
};
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 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&lt;=0) {
displayAnswer();
}
}
});
public TriviaOne() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,700);
frame.getContentPane().setBackground(new Color(204,229,255));
frame.setLayout(null);
frame.setResizable(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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,Font.PLAIN,30));
textarea.setLocation(16, 84);
textarea.setEditable(false);
buttonA.setBounds(50,200,50,50);
buttonA.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonA.setFocusable(false);
buttonA.addActionListener(this);
buttonA.setText(&quot;A&quot;);
buttonB.setBounds(50,300,50,50);
buttonB.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonB.setFocusable(false);
buttonB.addActionListener(this);
buttonB.setText(&quot;B&quot;);
buttonC.setBounds(50,400,50,50);
buttonC.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonC.setFocusable(false);
buttonC.addActionListener(this);
buttonC.setText(&quot;C&quot;);
buttonD.setBounds(50,500,50,50);
buttonD.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonD.setFocusable(false);
buttonD.addActionListener(this);
buttonD.setText(&quot;D&quot;);
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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,Font.PLAIN,35));
time_label.setHorizontalAlignment(JTextField.CENTER);
time_label.setText(&quot;Timer&quot;);
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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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&gt;=total_questions) {
results();
}
else {
textfield.setText(&quot;Question &quot;+(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) {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
if(e.getSource()==buttonA) {
answer= &#39;A&#39;;
if(answer == answers[index]) {
correct_guesses++;
}
}
if(e.getSource()==buttonB) {
answer= &#39;B&#39;;
if(answer == answers[index]) {
correct_guesses++;
}
}
if(e.getSource()==buttonC) {
answer= &#39;C&#39;;
if(answer == answers[index]) {
correct_guesses++;
}
}
if(e.getSource()==buttonD) {
answer= &#39;D&#39;;
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] != &#39;A&#39;)
answer_labelA.setForeground(new Color(255, 0, 0));
if(answers[index] != &#39;B&#39;)
answer_labelB.setForeground(new Color(255, 0, 0));
if(answers[index] != &#39;C&#39;)
answer_labelC.setForeground(new Color(255, 0, 0));
if(answers[index] != &#39;D&#39;)
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 = &#39; &#39;;
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(&quot;RESULTS!&quot;);
textarea.setText(&quot;&quot;);
answer_labelA.setText(&quot;&quot;);
answer_labelB.setText(&quot;&quot;);
answer_labelC.setText(&quot;&quot;);
answer_labelD.setText(&quot;&quot;);
number_right.setText(&quot;(&quot;+correct_guesses+&quot;/&quot;+total_questions+&quot;)&quot;);
percentage.setText(result+&quot;%&quot;);
frame.add(number_right);
frame.add(percentage);
}
}

This is the code for my start page..
I'm not that of a expert of a java btw...

  import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Quiz implements ActionListener {
JFrame frame = new JFrame();
JTextField titleName = new JTextField();
JTextArea subtitle = new JTextArea();
JButton startButton = new JButton();
public Quiz() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,700);
frame.getContentPane().setBackground(new Color(204,229,255));
frame.setLayout(null);
frame.setResizable(false);
titleName.setBounds(100, 100, 450, 150);
titleName.setBackground(new Color(204,229,255));
titleName.setForeground(new Color(0,102,204));
titleName.setFont(new Font(&quot;Roboto Condensed&quot;,Font.BOLD,80));
titleName.setText(&quot;TRIVIA&quot;);
subtitle.setText(&quot;Made by &quot;);
subtitle.setForeground(new Color(0,102,204));
subtitle.setFont(new Font(&quot;Roboto Condensed&quot;,Font.BOLD,30));
startButton = new JButton(&quot;START&quot;);
startButton.setFont(new Font(&quot;Roboto Condensed&quot;, Font.PLAIN,25));
startButton.setBounds(200, 400, 250, 100);
startButton.setBackground(new Color(153, 204, 255));
startButton.addActionListener(this);
frame.add(titleName);
frame.add(subtitle);
frame.add(startButton);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

This is the combined part

 import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TriviaOne implements ActionListener{
//Questions that will be in the trivia 
String[] questions = 	{
&quot;Select the official name of the coronavirus.&quot;,
&quot;When did the corona virus first ecountered?&quot;,
&quot;What is the percentage of people recovering from the coronavirus?&quot;,
&quot;Which below is NOT the symptom of coronavirus?&quot;,
&quot;Which part of the human body does the    coronavirus attach itself to?&quot;,
&quot;How many hour can the coronavirus survive on plastic and stainless steel surfaces?&quot;,
&quot;Whihc human organs in the body does the coronavirus attack?&quot;,
&quot;How large is the coronavirus?&quot;,
&quot;Which is a safe distance to stay apart from people? &quot;,
&quot;Who has the highest risk of getting infected by coronvirus?&quot;,
&quot;When should face masks be worn?&quot;,
&quot;Which is more effective for removing the coronavirus from your hands?&quot;,
&quot;Which industry includes workers with increased exposure-risk?&quot;,
&quot;What is the period of quartine?&quot;,
&quot;What is the name of the city where coronavirus    was first detected?&quot;
};
//the 4 answer choices that leads the user to choose
String[][] options = 	{
{&quot;COVID-19&quot;,&quot;Sars-CoV-2&quot;,&quot;Zaire ebolavirus&quot;,&quot;Influenza&quot;},
{&quot;2018&quot;,&quot;2020&quot;,&quot;2017&quot;,&quot;2019&quot;},
{&quot;63%&quot;,&quot;71%&quot;,&quot;80%&quot;,&quot;76%&quot;},
{&quot;Fever&quot;,&quot;Blurred vision&quot;,&quot;Dry Cough&quot;,&quot;Nasal Congestion&quot;},
{&quot;Red Blood Cells&quot;, &quot;Antigens&quot;, &quot;White Blood Cells&quot;, &quot;Ace-2 recpetors in the airways&quot;},
{&quot;4-8 hours&quot;, &quot;72 hours and more&quot;, &quot;45-60 hours&quot;, &quot;90 hours and more&quot; },
{&quot;Liver&quot;, &quot;Lungs&quot;, &quot;Heart&quot;, &quot;Kidney&quot;},
{&quot;8000 billionths of metre in diameter&quot;, &quot;800 billionths of metre in diameter&quot;,&quot;80 billionths of metre in diameter&quot;,&quot;8 billionths of metre in diameter&quot;},
{&quot;3 feet(1 meter)&quot;, &quot;2 feet(60 cm)&quot;, &quot;1 foot (30cm)&quot;, &quot;4.2 feet(1.3 meter)&quot;},
{&quot;Children&quot;, &quot;Pregnant Women&quot;, &quot;People over 60 years of age&quot;, &quot;30-40 years agr of men&quot;},
{&quot;Public Transport&quot;, &quot;Confined or Crowed spaces&quot;, &quot;Small restaurants or shops&quot;, &quot;All of the above&quot;},
{&quot;Soap and water&quot;, &quot;Alcohol-based hand sanitiser&quot;,&quot;Detergent&quot;, &quot;Face cleanser&quot;},
{&quot;Health care&quot;, &quot;Airline operations&quot;, &quot;Waste management&quot;, &quot;All of the above&quot;},
{&quot;21 days&quot;,&quot;7 days&quot;, &quot;14 days&quot;, &quot;6 days&quot;},
{&quot;Wuhan&quot;, &quot;Hubei&quot;, &quot;Hunan&quot;,&quot;Shanghai&quot;}
};
//correct answers for the following questions
char[] answers = 		{
&#39;A&#39;,
&#39;D&#39;,
&#39;C&#39;,
&#39;B&#39;,
&#39;D&#39;,
&#39;B&#39;,
&#39;B&#39;,
&#39;C&#39;,
&#39;A&#39;,
&#39;C&#39;,
&#39;D&#39;,
&#39;A&#39;,
&#39;D&#39;,
&#39;C&#39;,
&#39;A&#39;
};
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 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&lt;=0) {
displayAnswer();
}
}
});
public TriviaOne() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,700);
frame.getContentPane().setBackground(new Color(204,229,255));
frame.setLayout(null);
frame.setResizable(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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,Font.PLAIN,30));
textarea.setLocation(16, 84);
textarea.setEditable(false);
buttonA.setBounds(50,200,50,50);
buttonA.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonA.setFocusable(false);
buttonA.addActionListener(this);
buttonA.setText(&quot;A&quot;);
buttonB.setBounds(50,300,50,50);
buttonB.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonB.setFocusable(false);
buttonB.addActionListener(this);
buttonB.setText(&quot;B&quot;);
buttonC.setBounds(50,400,50,50);
buttonC.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonC.setFocusable(false);
buttonC.addActionListener(this);
buttonC.setText(&quot;C&quot;);
buttonD.setBounds(50,500,50,50);
buttonD.setFont(new Font(&quot;PT Serif&quot;,Font.BOLD,33));
buttonD.setFocusable(false);
buttonD.addActionListener(this);
buttonD.setText(&quot;D&quot;);
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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,Font.PLAIN,35));
time_label.setHorizontalAlignment(JTextField.CENTER);
time_label.setText(&quot;Timer&quot;);
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(&quot;PT Serif&quot;,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(&quot;PT Serif&quot;,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&gt;=total_questions) {
results();
}
else {
textfield.setText(&quot;Question &quot;+(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) {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
if(e.getSource()==buttonA) {
answer= &#39;A&#39;;
if(answer == answers[index]) {
correct_guesses++;
}
}
if(e.getSource()==buttonB) {
answer= &#39;B&#39;;
if(answer == answers[index]) {
correct_guesses++;
}
}
if(e.getSource()==buttonC) {
answer= &#39;C&#39;;
if(answer == answers[index]) {
correct_guesses++;
}
}
if(e.getSource()==buttonD) {
answer= &#39;D&#39;;
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] != &#39;A&#39;)
answer_labelA.setForeground(new Color(255, 0, 0));
if(answers[index] != &#39;B&#39;)
answer_labelB.setForeground(new Color(255, 0, 0));
if(answers[index] != &#39;C&#39;)
answer_labelC.setForeground(new Color(255, 0, 0));
if(answers[index] != &#39;D&#39;)
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 = &#39; &#39;;
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(&quot;RESULTS!&quot;);
textarea.setText(&quot;&quot;);
answer_labelA.setText(&quot;&quot;);
answer_labelB.setText(&quot;&quot;);
answer_labelC.setText(&quot;&quot;);
answer_labelD.setText(&quot;&quot;);
number_right.setText(&quot;(&quot;+correct_guesses+&quot;/&quot;+total_questions+&quot;)&quot;);
percentage.setText(result+&quot;%&quot;);
frame.add(number_right);
frame.add(percentage);
}
}

答案1

得分: 2

以下是翻译好的内容:

  1. Swing 需要处理多个 PLAFs、操作系统、屏幕尺寸和分辨率,这就是为什么应该避免像素完美的 GUI,因为你可能会遇到这种问题(而且你已经遇到了),我敢打赌你的电脑上问题没有被裁剪,按钮包含一个字母而不仅仅是 ...,这意味着你的内容不适合按钮的大小。因此,避免使用 setLayout(null).setBounds(...)。参考为什么不推荐使用 null 布局? 进一步了解。

  2. 对于类似问答游戏的程序,最好的布局之一是CardLayout,这样可以在面板之间切换。这里 是一个简单的使用示例。

  3. 避免在 JFrame 上使用 setSize(...),推荐在 JPanel 上覆盖 getPreferredSize,然后使用 pack() 设置 JFrame 的大小,这样它将添加窗口装饰,不会影响 UI 大小,参考我应该避免使用 setPreferred|Maximum|MinimumSize 方法吗?(是的)

  4. 学习如何使用数组和集合,比如 List,这将大大改善代码,减少其中重复的代码行,使代码更易读懂。

  5. 在变量命名方面保持一致,Java 命名约定 规定变量应使用 camelCase,不要使用下划线。

    • 首字母大写的类名
    • 首字母小写的变量名
    • 首字母小写的方法名()
    • 全部大写的常量名
  6. 不要将所有的问题、答案和正确答案的数组分散在三个不同的数组中,将它们移到一个模型类中,根据需要为每个问题创建 N 个实例(列表和数组在这里很有用)。

  7. 你提到的第一个屏幕应该是 JDialogJOptionPane,我认为结果屏幕也是如此。

  8. 同样避免使用多个 JFrame,这会造成糟糕的用户体验,参考使用多个 JFrames,好的还是不好的做法?(不好)

上述建议中,下面是一个与你的 UI 非常相似的代码示例,我没有添加所有的功能,但这应该足够帮助你朝正确的方向迈进:

//(略,此处为翻译后的 Java 代码示例)

希望这些翻译对你有帮助。如果有任何进一步的翻译需求,请随时提问。

英文:

Phew! Where do I start with your program? It's wrong in a lot of ways:

  1. Swing has to deal with multiple PLAFs, OS, screen sizes and resolutions, that's why pixel perfect GUIs should be avoided, as you might run into this kind of issues (and you did), as I bet your questions aren't cropped in your computer and the buttons contain a letter and not just ... which means that your content isn't fitting the size of the button. So avoid the use of setLayout(null) and .setBounds(...). See Why is it frowned upon to use null layout? to expand on this.

    无法在基于GUI的Java程序中添加标题页

  2. For Quiz-like programs, one of the best layouts to use is CardLayout, this will allow you to switch between panels. Here is a simple example of how to use it.

  3. Avoid the use of setSize(...) on the JFrame, it's recommended to instead override getPreferredSize on the JPanel and then pack() your JFrame, this way, it will add the window decorations apart from your UI size, see Should I avoid the use of setPreferred|Maximum|MinimumSize? (Yes)

  4. Learn how to use arrays and collections such as List, this will greatly improve your code and reduce the repetitive lines of code in it, make it easier to read and understand.

  5. Be consistent with your variable namings, Java naming conventions state that your variables should be written in camelCase, without underscores.

    • FirstWordUpperCaseClass
    • firstWordLowerCaseVariable
    • firstWordLowerCaseMethod()
    • ALL_WORDS_UPPER_CASED_CONSTANT
  6. Instead of having all your questions and answers and which answer is the correct one in 3 different arrays, move them into a Model class and create N instances of it as needed for every question (again, lists and arrays are your friends here).

  7. The first screen you mention, should be a JDialog or JOptionPane, and I'd say the results screen as well.

  8. Also avoid the use of multiple JFrames, it creates a horrible UX, see The use of multiple JFrames, good / bad practice? (Bad)

With all the above recommendations, here's a very similar UI to yours, I didn't add all the functionality but this should be enough for a step in the right direction:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
//This is the main class, it contains the CardLayout
public class QuizOne {
private JFrame frame;
private QuestionPane[] cards;
private JPanel pane;
private CardLayout cl;
private JLabel timerLabel;
private List&lt;QuizQuestion&gt; questions;
private Timer temporaryTimer;
public static void main(String[] args) {
//We place our program on the EDT using Java 8 lambdas
SwingUtilities.invokeLater(new QuizOne()::createAndShowGUI);
}
//Here&#39;s where the magic happens
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName()); //Get the class name and set it as the frame&#39;s title
cl = new CardLayout(); //Create a new CardLayout
pane = new JPanel(cl); //Set the CardLayout to this JPanel
temporaryTimer = new Timer(500, event -&gt; { //The timer to show the result of the answer for half second before switching to the new one.
cl.next(pane); //This moves the CardLayout to the next one
temporaryTimer.stop(); //We stop this timer when we switch to the next card.
});
generateQuestionsAndAnswers(); //We populate the model of questions with their answers here.
cards = new QuestionPane[questions.size()];
for (int i = 0; i &lt; cards.length; i++) {
cards[i] = new QuestionPane(questions.get(i), i, pane, cl, cards.length, frame, temporaryTimer); //We create a new QuestionPane and send some information as parameters
pane.add(cards[i], &quot;question&quot; + i); //We add the card to the CardLayout pane
}
timerLabel = new JLabel(&quot;Time: &quot;);
UIManager.put(&quot;OptionPane.okButtonText&quot;, &quot;Start Quiz&quot;); //We change the &quot;OK&quot; from the JOptionPane button to &quot;Start Quiz&quot;
int option = JOptionPane.showConfirmDialog(frame, new JLabel(&quot;Click button to start quiz&quot;), &quot;Welcome&quot;, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
if (option == JOptionPane.OK_OPTION) {
//Start your timer for the first question
}
frame.add(pane); //We add the CardLayout pane to our JFrame&#39;s CENTER position
frame.add(timerLabel, BorderLayout.SOUTH); //And the timerLabel at the bottom
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); //
}
//We create an ArrayList of QuizQuestion that each has their own question, the possible answers and the correct answer (index + 1)
private void generateQuestionsAndAnswers() {
questions = new ArrayList&lt;&gt;();
questions.add(new QuizQuestion(&quot;Select the official name of the coronavirus.&quot;, new String[] {&quot;COVID-19&quot;,&quot;Sars-CoV-2&quot;,&quot;Zaire ebolavirus&quot;,&quot;Influenza&quot;}, 1));
questions.add(new QuizQuestion(&quot;When did the corona virus first ecountered?&quot;, new String[] {&quot;2018&quot;,&quot;2020&quot;,&quot;2017&quot;,&quot;2019&quot;}, 4));
questions.add(new QuizQuestion(&quot;What is the percentage of people recovering from the coronavirus?&quot;, new String[] {&quot;63%&quot;,&quot;71%&quot;,&quot;80%&quot;,&quot;76%&quot;}, 3));
questions.add(new QuizQuestion(&quot;Which below is NOT the symptom of coronavirus?&quot;, new String[] {&quot;Fever&quot;,&quot;Blurred vision&quot;,&quot;Dry Cough&quot;,&quot;Nasal Congestion&quot;}, 2));
questions.add(new QuizQuestion(&quot;Which part of the human body does the coronavirus attach itself to?&quot;, new String[] {&quot;Red Blood Cells&quot;, &quot;Antigens&quot;, &quot;White Blood Cells&quot;, &quot;Ace-2 recpetors in the airways&quot;}, 4));
}
}
@SuppressWarnings(&quot;serial&quot;)
class ResultsPane extends JPanel { //This is a class that will create a simple JPanel with vertical alignment to add the number of correct answers, accuracy and a text for the user if they want to retry
public ResultsPane(int correctAnswers, int totalQuestions) {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
float percentage = ((float) (correctAnswers) / (float) (totalQuestions)) * 100;
add(new JLabel(&quot;Correct Answers: &quot; + correctAnswers + &quot; / &quot; + totalQuestions));
add(new JLabel(&quot;Accuracy: &quot; + percentage + &quot;%&quot;));
add(new JLabel(&quot;Want to Retry?&quot;));
}
}
@SuppressWarnings(&quot;serial&quot;)
class QuestionPane extends JPanel { //This is the pane in which each card will be displayed
private JButton[] answersButtons; //Array of buttons for the answers instead of 4 individual buttons
private JLabel questionLabel;
private JLabel questionNumber;
private JLabel[] answerLabels; //Same for the labels
private static int correctAnswers = 0; //This is static to count all the correct answers in all the instances
public QuestionPane(QuizQuestion question, int currentQuestion, JPanel pane, CardLayout cl, int totalQuestions, JFrame frame, Timer timer) { //Probably this isn&#39;t the most elegant solution to send multiple objects as parameters here, as it makes the program tightly coupled.
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
questionNumber = new JLabel(&quot;Question &quot; + (currentQuestion + 1), SwingConstants.CENTER); //We set the question number on top and center the text
questionLabel = new JLabel(question.getQuestion()); // We set the question text to this label
answerLabels = new JLabel[question.getAnswers().length]; //We create our array of 4 labels and 4 buttons below
answersButtons = new JButton[question.getAnswers().length];
for (int i = 0; i &lt; question.getAnswers().length; i++) {
answersButtons[i] = new JButton(String.valueOf((char) (&#39;A&#39; + i))); // This will set the buttons text to A, B, C, D
answersButtons[i].addActionListener(e -&gt; { //ActionListener using Java 8 lambdas
if (e.getActionCommand().charAt(0) - &#39;A&#39; == question.getCorrectAnswer() - 1) { //Here we check if the button clicked was the one with the correct answer, converting the text from A-D to 0-3 and compare it to the index - 1 from the question model
correctAnswers++; //Increase the correctAnswer + 1
answerLabels[e.getActionCommand().charAt(0) - &#39;A&#39;].setBackground(Color.GREEN); //Set the background color to green if it was correct
} else {
answerLabels[e.getActionCommand().charAt(0) - &#39;A&#39;].setBackground(Color.RED); //Or red otherwise
}
if (currentQuestion == totalQuestions - 1) { //If we reach the end of questions, show the results screen
int input = JOptionPane.showConfirmDialog(pane, new ResultsPane(correctAnswers, totalQuestions), &quot;Results&quot;, JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
if (input == JOptionPane.YES_OPTION) {
//Reset everything and show your GUI again
} else {
frame.dispose(); //If user says they don&#39;t want to retry, dispose the frame.
}
} else {
timer.start(); //Start the timer that will display the results for half a second.
}
});
}
add(questionNumber); //Add the question number
add(questionLabel); //The question text
for (int i = 0; i &lt; question.getAnswers().length; i++) {
JPanel answerPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); //Create a new JPanel for each label and button and make them left aligned
answerPane.add(answersButtons[i]); //Add every button
answerLabels[i] = new JLabel(question.getAnswers()[i]); //Create a new label with each answer&#39;s text
answerLabels[i].setOpaque(true); //Make them opaque (for the background colors later)
answerPane.add(answerLabels[i]); //And add them to the pane
add(answerPane); //Then add the pane to the wrapping pane
}
}
}
//A simple model for your questions.
class QuizQuestion {
private String question;
private String[] answers;
private int correctAnswer;
public QuizQuestion(String question, String[] answers, int correctAnswer) {
super();
this.question = question;
this.answers = answers;
this.correctAnswer = correctAnswer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String[] getAnswers() {
return answers;
}
public void setAnswers(String[] answers) {
this.answers = answers;
}
public int getCorrectAnswer() {
return correctAnswer;
}
public void setCorrectAnswer(int correctAnswer) {
this.correctAnswer = correctAnswer;
}
}

And some SS of the program, note that I didn't include formatting as I'm leaving that part to you, trying to keep things simple here.

无法在基于GUI的Java程序中添加标题页 无法在基于GUI的Java程序中添加标题页 无法在基于GUI的Java程序中添加标题页 无法在基于GUI的Java程序中添加标题页

huangapple
  • 本文由 发表于 2020年7月27日 20:18:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63115171.html
匿名

发表评论

匿名网友

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

确定