2014-07-22 33 views
1

如何讓Swing Timer對象每兩秒觸發十次並在每次觸發中做一件不同的事情?使用:如何使用Java Swing Timer在每次觸發時執行不同的操作?

// task one 

int delay = 2000; 

Timer swingTimer = new Timer(delay, new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 

     // task two 
    } 
}); 
swingTimer.start(); 

只能讓我做兩件事。但是我想用計時器來執行一個代碼塊,等待2秒鐘,執行另一個代碼塊,等待另外2秒鐘,做另一件事等等等等等等,以等待10個連續的任務。謝謝。

回答

2

使用某種計數器,在你的actionPerformed方法來確定哪些週期的多達....

private int cycle = 0; 

//... 

Timer swingTimer = new Timer(delay, new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     switch (cycle) { 
      case 0: 
       // Task #1 
       break; 
      case 1: 
       // Task #2 
       break; 
      case 2: 
       // Task #3 
       break; 
      default: 
       // All done... 
       ((Timer)e.getSource()).stop(); 
     } 
     cycle++; 
    } 
}); 

你可以建立一個新的非重複每個actionPerformed結束Timer,它播種隨着下一個ActionListener /任務被執行,但這可以很快凌亂...

這是這個想法的基本概念。您可以爲每個任務設計一個通用的interface,將它們添加到某種List,並簡單地使用list.remove(0)來彈出List中的下一個並執行它。您需要等到List爲空。

+0

ALLAH RAZI OLSUN。 ALLAH TUTTUGUNU ALTINETSİN。 – user3862572

2
private int cycle; 

Timer swingTimer = new Timer(delay, new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     controller.callMethod(cycle); // controller decides what to do 
     cycle++; 
    } 
}); 

並且不要忘記在完成所需的週期數後停止計時器。

相關問題