Java )->createAndShowGui(问题列表); } }
此代码中的GUi如下所示:Java )->createAndShowGui(问题列表); } },java,swing,variables,jbutton,actionlistener,Java,Swing,Variables,Jbutton,Actionlistener,此代码中的GUi如下所示: 这里的逻辑是错误的: private static class ButtonHandler implements ActionListener { public void actionPerformed (ActionEvent e) { if (e.getSource () == btnT1) { frame2.setVisible (true); btnT1.setE
这里的逻辑是错误的:
private static class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if (e.getSource () == btnT1)
{
frame2.setVisible (true);
btnT1.setEnabled (false);
qTitle.setText ("Solar energy generates electricity from what source?");
a1.setText ("The water");
a2.setText ("The sun");
a3.setText ("Fossil fuels");
a4.setText ("The wind");
if (e.getSource () == a2)
{
score = score + 100;
frame2.setVisible (false);
}
else if (e.getSource () != a2)
{
lives = lives - 1;
frame2.setVisible (false);
}
}
在按下任何a1、a2、a3或a4按钮之前,当按下btnT1时,此处理程序将被激活,因此在用户有机会做出选择之前,您正在进行逻辑测试
要使其工作,a1、a2、a3和a4上的侦听器需要具有该侦听器所具有的逻辑
如果这是我的程序,我会将我的GUI(“视图”)与程序的逻辑部分(“模型”)分离,我会创建一个非GUI问题类,一个包含问题文本、包含正确答案、可以检查正确性的类,以及一个GUI问题视图,这将显示问题,并可以根据它所持有的模型(问题)检查用户的响应——我将把整个事情划分开来,而不是像您所做的那样硬编码
作为旁白,请阅读
例如,我将为Question创建一个单独的类,一个非GUI类,其中包含一个问题字符串、一个答案字符串和一个可能的回答列表,该列表包含用户可以选择的所有答案,类似这样的方法可以工作:
public class Question {
private String question;
private List<String> possibleAnswers;
private String answer;
public Question(String question, List<String> possibleAnswers, String answer) {
this.question = question;
this.answer = answer;
// randomize things:
this.possibleAnswers = new ArrayList<>(possibleAnswers);
Collections.shuffle(this.possibleAnswers);
}
public String getQuestion() {
return question;
}
public List<String> getPossibleAnswers() {
return possibleAnswers;
}
public String getAnswer() {
return answer;
}
// test if String matches answer
public boolean test(String possibleAnswer) {
return answer.equals(possibleAnswer);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Q: ");
sb.append(question);
sb.append("; ");
sb.append("A: ");
sb.append(answer);
sb.append("; ");
sb.append(possibleAnswers);
return sb.toString();
}
}
我将创建代码逐行读取该文件,在读取时创建问题对象,并将它们放入ArrayList
然后,我将创建一个JPanel,将单个问题显示为GUI,使用JLabel来显示问题字符串,在嵌套的JPanel中保存一组JRadioButton,使用GridLayout保存可能的答案字符串,以及一个JButton来提交用户的评分选择
例如:
@SuppressWarnings("serial")
public class QuestionViewPanel extends JPanel {
private Question question; // model for this view
private JLabel questionLabel;
private ButtonGroup answersGroup = new ButtonGroup();
private JButton submitButton = new JButton("Submit");
private JButton clearAnswerButton = new JButton("Clear Answer");
public QuestionViewPanel(Question question) {
this.question = question;
questionLabel = new JLabel(question.getQuestion());
questionLabel.setBorder(BorderFactory.createTitledBorder("Question:"));
JPanel possAnswersPanel = new JPanel(new GridLayout(0, 1));
possAnswersPanel.setBorder(BorderFactory.createTitledBorder("Possible Answers:"));
for (String possAnswer : question.getPossibleAnswers()) {
JRadioButton rBtn = new JRadioButton(possAnswer);
rBtn.setActionCommand(possAnswer);
answersGroup.add(rBtn);
possAnswersPanel.add(rBtn);
}
clearAnswerButton.setMnemonic(KeyEvent.VK_C);
clearAnswerButton.addActionListener(e -> answersGroup.clearSelection());
submitButton.setMnemonic(KeyEvent.VK_S);
JPanel bottomPanel = new JPanel();
bottomPanel.add(submitButton);
bottomPanel.add(clearAnswerButton);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(questionLabel, BorderLayout.PAGE_START);
add(possAnswersPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public void addSubmitListener(ActionListener listener) {
submitButton.addActionListener(listener);
}
public Question getQuestion() {
return question;
}
public boolean testAnswer() {
boolean result = false;
ButtonModel model = answersGroup.getSelection();
if (model != null) {
String possibleAnswer = model.getActionCommand();
result = question.test(possibleAnswer);
}
return result;
}
}
然后创建一个快速而肮脏的驱动程序类,一个创建GUI的类,一个使用CardLayout交换问题视图面板的类,一个将事物组合在一起的类:
@SuppressWarnings("serial")
public class QuestionTest extends JPanel {
// This String likely needs to be changed
private static final String RESOURCE_PATH = "QuestionsFile.txt";
private List<Question> questionsList = new ArrayList<>();
private List<QuestionViewPanel> questionViewList = new ArrayList<>();
private CardLayout cardLayout = new CardLayout();
private JPanel questionViewShowPanel = new JPanel(cardLayout);
public QuestionTest(List<Question> questionsList) {
this.questionsList = questionsList;
for (Question question : questionsList) {
QuestionViewPanel qView = new QuestionViewPanel(question);
qView.addSubmitListener(new SubmitListener(qView));
questionViewShowPanel.add(qView, question.getQuestion());
}
setLayout(new BorderLayout());
add(questionViewShowPanel);
}
private class SubmitListener implements ActionListener {
private QuestionViewPanel qView;
public SubmitListener(QuestionViewPanel qView) {
this.qView = qView;
}
@Override
public void actionPerformed(ActionEvent e) {
boolean result = qView.testAnswer();
String text = result ? "Correct!" : "Wrong! The correct answer is: "
+ qView.getQuestion().getAnswer();
JOptionPane.showMessageDialog(qView, text, "Result", JOptionPane.PLAIN_MESSAGE);
cardLayout.next(questionViewShowPanel);
}
}
private static void createAndShowGui(List<Question> questionsList) {
QuestionTest mainPanel = new QuestionTest(questionsList);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
final List<Question> questionsList = new ArrayList<>();
InputStream questionsStream = QuestionTest.class.getResourceAsStream(RESOURCE_PATH);
Scanner scanner = new Scanner(questionsStream);
String question = "";
String answer = "";
List<String> possibleAnswers = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.trim().isEmpty()) {
if (!question.trim().isEmpty()) {
questionsList.add(new Question(question, possibleAnswers, answer));
question = "";
answer = "";
possibleAnswers = new ArrayList<>();
}
} else if (question.trim().isEmpty()) {
question = line;
} else {
possibleAnswers.add(line);
if (answer.trim().isBlank()) {
answer = line;
}
}
}
if (!question.trim().isEmpty()) {
questionsList.add(new Question(question, possibleAnswers, answer));
question = "";
answer = "";
possibleAnswers = new ArrayList<>();
}
if (scanner != null) {
scanner.close();
}
SwingUtilities.invokeLater(() -> createAndShowGui(questionsList));
}
}
@SuppressWarnings(“串行”)
公共类问题测试扩展了JPanel{
//此字符串可能需要更改
私有静态最终字符串资源\u PATH=“QuestionsFile.txt”;
私有列表问题列表=新的ArrayList();
私有列表questionViewList=新建ArrayList();
private CardLayout CardLayout=新的CardLayout();
private JPanel questionViewShowPanel=新JPanel(cardLayout);
公共问题测试(列表问题列表){
this.questionsList=问题列表;
for(问题:问题列表){
QuestionViewPanel qView=新的QuestionViewPanel(问题);
addSubmitListener(新SubmitListener(qView));
questionViewShowPanel.add(qView,question.getQuestion());
}
setLayout(新的BorderLayout());
添加(问题视图显示面板);
}
私有类SubmitListener实现ActionListener{
私人问题视图面板qView;
公共提交者列表(问题视图面板qView){
this.qView=qView;
}
@凌驾
已执行的公共无效操作(操作事件e){
布尔结果=qView.testAnswer();
字符串文本=结果?“正确!”:“错误!正确答案是:”
+qView.getQuestion().getAnswer();
showMessageDialog(qView,文本,“结果”,JOptionPane.PLAIN_消息);
cardLayout.next(问题视图显示面板);
}
}
私有静态void createAndShowGui(列表问题列表){
QuestionTest主面板=新的QuestionTest(问题列表);
JFrame=新JFrame(“测试”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(主面板);
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
公共静态void main(字符串[]args){
最终列表问题列表=新的ArrayList();
InputStream questionsStream=QuestionTest.class.getResourceAsStream(资源路径);
扫描仪=新扫描仪(问题流);
字符串问题=”;
字符串答案=”;
List-possibleAnswers=new-ArrayList();
while(scanner.hasNextLine()){
字符串行=scanner.nextLine();
if(line.trim().isEmpty()){
如果(!question.trim().isEmpty()){
问题列表。添加(新问题(问题、可能答案、答案));
问题=”;
答案=”;
possibleAnswers=newarraylist();
}
}else if(question.trim().isEmpty()){
问题=行;
}否则{
可能的答案。添加(行);
if(answer.trim().isBlank()){
答案=行;
}
}
}
如果(!question.trim().isEmpty()){
问题列表。添加(新问题(问题、可能答案、答案));
问题=”;
答案=”;
possibleAnswers=newarraylist();
}
如果(扫描器!=null){
scanner.close();
}
调用器(()->createAndShowGui(问题列表));
}
}
此代码中的GUi如下所示:
1。通过巧妙地使用数组、集合和循环,可以减少大量重复代码。2.这样做可以使代码更容易调试。3.如果您需要我们帮助您找出代码不起作用的原因,最好在您的问题中创建并发布一个有效的/程序。否则我们真的无法测试此代码。当您的侦听器被激活时,源代码是
btnT1
。在用户有时间与新问题交互之前,它不会神奇地变为a1、a2或a3,因此按钮侦听器实际上没有多大意义。这就像你在问用户是否在用户有机会做出选择之前做出了正确的选择。1。通过巧妙地使用数组、集合和循环,可以减少大量重复代码。2.做
Who is buried in Grant's tomb?
Ulysses Grant
George Washington
Abraham Lincoln
Donald Trump
What color was Washington's white horse?
White
Blue
Green
Brown
How many days are there in a week?
7
4
2
3
What is 2 + 2?
4
2
11
I have no idea?
What is the largest celestial body in the solar system?
The sun
Jupiter
Mars
What is the solar system?
@SuppressWarnings("serial")
public class QuestionViewPanel extends JPanel {
private Question question; // model for this view
private JLabel questionLabel;
private ButtonGroup answersGroup = new ButtonGroup();
private JButton submitButton = new JButton("Submit");
private JButton clearAnswerButton = new JButton("Clear Answer");
public QuestionViewPanel(Question question) {
this.question = question;
questionLabel = new JLabel(question.getQuestion());
questionLabel.setBorder(BorderFactory.createTitledBorder("Question:"));
JPanel possAnswersPanel = new JPanel(new GridLayout(0, 1));
possAnswersPanel.setBorder(BorderFactory.createTitledBorder("Possible Answers:"));
for (String possAnswer : question.getPossibleAnswers()) {
JRadioButton rBtn = new JRadioButton(possAnswer);
rBtn.setActionCommand(possAnswer);
answersGroup.add(rBtn);
possAnswersPanel.add(rBtn);
}
clearAnswerButton.setMnemonic(KeyEvent.VK_C);
clearAnswerButton.addActionListener(e -> answersGroup.clearSelection());
submitButton.setMnemonic(KeyEvent.VK_S);
JPanel bottomPanel = new JPanel();
bottomPanel.add(submitButton);
bottomPanel.add(clearAnswerButton);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(questionLabel, BorderLayout.PAGE_START);
add(possAnswersPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public void addSubmitListener(ActionListener listener) {
submitButton.addActionListener(listener);
}
public Question getQuestion() {
return question;
}
public boolean testAnswer() {
boolean result = false;
ButtonModel model = answersGroup.getSelection();
if (model != null) {
String possibleAnswer = model.getActionCommand();
result = question.test(possibleAnswer);
}
return result;
}
}
@SuppressWarnings("serial")
public class QuestionTest extends JPanel {
// This String likely needs to be changed
private static final String RESOURCE_PATH = "QuestionsFile.txt";
private List<Question> questionsList = new ArrayList<>();
private List<QuestionViewPanel> questionViewList = new ArrayList<>();
private CardLayout cardLayout = new CardLayout();
private JPanel questionViewShowPanel = new JPanel(cardLayout);
public QuestionTest(List<Question> questionsList) {
this.questionsList = questionsList;
for (Question question : questionsList) {
QuestionViewPanel qView = new QuestionViewPanel(question);
qView.addSubmitListener(new SubmitListener(qView));
questionViewShowPanel.add(qView, question.getQuestion());
}
setLayout(new BorderLayout());
add(questionViewShowPanel);
}
private class SubmitListener implements ActionListener {
private QuestionViewPanel qView;
public SubmitListener(QuestionViewPanel qView) {
this.qView = qView;
}
@Override
public void actionPerformed(ActionEvent e) {
boolean result = qView.testAnswer();
String text = result ? "Correct!" : "Wrong! The correct answer is: "
+ qView.getQuestion().getAnswer();
JOptionPane.showMessageDialog(qView, text, "Result", JOptionPane.PLAIN_MESSAGE);
cardLayout.next(questionViewShowPanel);
}
}
private static void createAndShowGui(List<Question> questionsList) {
QuestionTest mainPanel = new QuestionTest(questionsList);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
final List<Question> questionsList = new ArrayList<>();
InputStream questionsStream = QuestionTest.class.getResourceAsStream(RESOURCE_PATH);
Scanner scanner = new Scanner(questionsStream);
String question = "";
String answer = "";
List<String> possibleAnswers = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.trim().isEmpty()) {
if (!question.trim().isEmpty()) {
questionsList.add(new Question(question, possibleAnswers, answer));
question = "";
answer = "";
possibleAnswers = new ArrayList<>();
}
} else if (question.trim().isEmpty()) {
question = line;
} else {
possibleAnswers.add(line);
if (answer.trim().isBlank()) {
answer = line;
}
}
}
if (!question.trim().isEmpty()) {
questionsList.add(new Question(question, possibleAnswers, answer));
question = "";
answer = "";
possibleAnswers = new ArrayList<>();
}
if (scanner != null) {
scanner.close();
}
SwingUtilities.invokeLater(() -> createAndShowGui(questionsList));
}
}