我是Java新手,我試圖在按下Jbutton start時添加一個時間延遲。我使用了TimeUnit.SECONDS.sleep(),但它不起作用,然后我研究并發現了java swing定時器,但它也不起作用,我不知道為什么
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("start DONE");
Object step;
for (int i = 1; i < n; i++) {
//code that shows on interface
// then i want a delay here then to carry on with the iteration of for
timer.start();
};
}
});
}
});
你就快到了。但你似乎誤解了
Timer
到底在為你做什么。Timer
作為一種偽循環,具有內置延遲。也就是說,在每個時間段之后,它將執行。這意味著,每次觸發ActionListener
時,您都希望執行邏輯中的下一步。For example...