繁体   English   中英

如何将信息从Override的ActionListener方法发送到Java中的main方法?

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

基本上,我是一个新手,正在创建一个程序,该程序给出问题,随机分配正确答案的索引,然后在JFrame中显示问题。 我可以轻松执行添加到此ActionListener方法的所有任务:

@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);
    }
}

该程序从main方法中给定的setActionCommand中获取“ 1”,但是我希望Listener返回到main方法中,以便在单击正确的单选按钮时,也将显示下一个问题。 主要方法如下所示:

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

因此,我需要程序在循环中等待,直到单击正确的答案为止。 我该如何实现?

正如其他人指出的那样,循环等待并不是处理Java中等待GUI用户输入的方法。

您可以改为重新设计程序,使其看起来像这样:

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

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

然后,您可以从ActionListener内简单地调用nextQuestion()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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