简体   繁体   中英

How do I send information from my Overridden ActionListener method to the main method in Java?

Basically, I'm a newbie creating a program that gives questions, randomizes the index of the right answer and then displays the questions in a JFrame. I can easily perform any tasks that I add to this ActionListener method:

@Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("1")) {
            System.out.println("whatever");
            JOptionPane.showMessageDialog(null, "correct!", 
                "", JOptionPane.PLAIN_MESSAGE);
        } else {
        JOptionPane.showMessageDialog(null, "wrong!", 
                "", JOptionPane.PLAIN_MESSAGE);
    }
}

The program gets the "1" from setActionCommand given in the main method, yet I want the Listener to return to the main method something that when the correct radiobutton is clicked, then the next question will be displayed as well. The main method is made like:

while (therearestillquestionsleft) { /* do everything */ }

so I need the program to wait in the loop until the right answer is clicked. How can I achieve that?

As others have pointed out, waiting in a loop is not the way to handle waiting for GUI user input in Java.

You could instead redesign your program to look something like this:

public static void main(String args[]) {
    // [...]
    nextQuestion();
}

public static void nextQuestion() {
    if (questionsLeft) {
        // "do everything", i.e. show next question
    }
}

Then, you can simply call nextQuestion() from within your ActionListener .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM