【问题标题】:traverse an array in GUI Java在 GUI Java 中遍历数组
【发布时间】:2021-05-31 09:40:21
【问题描述】:

我正在做一份带有问题和书面答案的问卷调查。 我需要在添加答案时,按主按钮,告诉我它是否正确,并向我展示数组的另一个问题,直到数组完成。这里我上传了整个代码。

mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
    for(int i=0;i<question;i++) {
        if(answer.getText()==(option[i])) {
        message.setText("is correct");
        corrects++;
                }
    else {
    message.setText("incorrect");
       }
  
};

【问题讨论】:

  • 听起来你需要一个动画库。 Swing 本身并不能使动画变得尽可能简单。相信GitHub上有项目可以添加这个
  • 到目前为止,您还没有指定任何问题,所以我不确定您期待什么答案。您可能需要编辑您的问题以明确您的要求。
  • 我们需要更多关于您想要达到的目标的信息
  • 我需要在回答问题并按下按钮时显示数组中的另一个问题
  • 仅靠一段代码是无法做到的,如果遇到错误,请尝试谷歌搜索并来这里。

标签: java arrays swing jframe guice


【解决方案1】:

您的想法是正确的,但您需要一次处理一个问题,而不是在 ActionListener 中一次处理所有问题。

解决此问题的一种方法是在动作侦听器之外跟踪问题,在本例中,我们使用int questionCounter = 0; 来跟踪当前问题,然后我们可以删除for 循环并处理问题一次一个。这是一个使用您的代码如何工作的简单示例,请注意我们如何重置字段并在每次回答上一个问题时添加下一个问题。

//Use a variable outside of the action listener to keep track of the current question:
int questionCounter = 0;

//Show first question in the text area:
area.setText(question[questionCounter]);

mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {

    if(answer.getText().equals(option[questionCounter])) {
        message.setText("The previous answer was correct");
        corrects++;
        //Update the total each time you get one correct
        correct_answers.setText("correct answers: "+corrects);
    }
    else {
        message.setText("The previous answer was incorrect");
    }
    
    //Increment for the next question    
    questionCounter++;

    //Check if there is another question, then show it
    if (questionCounter < question.length){
        answer.setText("");
        area.setText(question[questionCounter]);
    }
    //Show the overall results if there are no more answers to check
    else{
        area.setText("Quiz complete, you got " + corrects + " out of " + question.length + " correct.");
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2013-03-14
    • 2017-07-11
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多