[英]java wait for swing.timer task to finish before executing the next task
[英]Wait for Swing Timer to finish not working using a while loop
我想在執行順序代碼之前等待 Swing 計時器完成。 我在網上研究過,同一條線上的每個問題似乎都有很大不同,沒有具體的答案。 但是,我確實看到了使用 while 循環和確定計時器是否完成的布爾值的答案。
使用我在這里設置的代碼,我期望以下內容:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public boolean timerDone = false;
public Test() {
start();
System.out.println("Finished");
}
public void start() {
new Timer(100, new ActionListener() {
int i = 0;
public void actionPerformed(ActionEvent event) {
i++;
if(i == 5) {
timerDone = true;
((Timer)event.getSource()).stop();
}
}
}).start();
while(!timerDone);
}
}
然而,即使定時器代碼執行,while 循環也不會終止。 因此,我決定創建一個包含 while 循環的新線程:
Thread t = new Thread(() -> {
while(!timerDone);
});
t.start();
有了這個添加, println 語句“Finished”立即打印出來並且程序永遠不會終止。 要么 1. 我怎樣才能修復這個當前設置? 或 2. 如何正確等待 Swing Timer 終止?
而不是使用布爾標志( timerDone = true
)`調用一個方法來完成所需的工作:
import javax.swing.*;
public class Test {
private int counter;
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new Test());
}
public Test() {
start();
}
public void start() {
counter = 0;
new Timer(100, event -> {
counter++;
System.out.println("Timer is running "+ counter);
if(counter == 5) {
doAfterTimerStopped();
((Timer)event.getSource()).stop();
}
}).start();
}
private void doAfterTimerStopped(){
System.out.println("Timer finished");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.