[英]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.