2013-12-22 75 views
0

我以前見過這樣的帖子,但問題或答案不清楚,請耐心等待,如果你以前聽說過。我有一個計時器,我想在計時器關閉時發生一個ActionEvent。我不想使用javax.swing.Timer方法。如何才能做到這一點?沒有必要解釋,但這會有所幫助。我正在尋找類似的 ActionEvent.do()方法Java射擊動作事件

我的代碼:

/** 
* 
* @param millisec time in milliseconds 
* @param ae action to occur when time is complete 
*/ 
public BasicTimer(int millisec, ActionEvent ae){ 
    this.millisec = millisec; 
    this.ae = ae; 
} 

public void start(){ 
    millisec += System.currentTimeMillis(); 
    do{ 
     current = System.currentTimeMillis(); 
    }while(current < millisec); 

} 

謝謝! Dando18

+1

*「我見過的帖子這樣過,但他們沒有問及」 * ...什麼是巧合... –

+0

只需使用'Timer'。你的實現似乎是單線程的。 –

+0

@SotiriosDelimanolis我想知道如何在沒有Timer的情況下做到這一點。 – Dando18

回答

0

這裏有一些簡單的計時器實現。爲什麼你只是沒有檢查其他計時器的工作原理?

public class AnotherTimerImpl { 

     long milisecondsInterval; 
     private ActionListener listener; 
     private boolean shouldRun = true; 

     private final Object sync = new Object(); 

     public AnotherTimerImpl(long interval, ActionListener listener) { 
      milisecondsInterval = interval; 
      this.listener = listener; 
     } 

     public void start() { 
      setShouldRun(true); 
      ExecutorService executor = Executors.newSingleThreadExecutor(); 
      executor.execute(new Runnable() { 

       @Override 
       public void run() { 
        while (isShouldRun()) { 
         listener.actionPerformed(null); 
         try { 
          Thread.sleep(milisecondsInterval); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
          break; 
         } 
        } 

       } 
      }); 
     } 

     public void stop() { 
      setShouldRun(false); 
     } 

     public boolean isShouldRun() { 
      synchronized (sync) { 
       return shouldRun; 
      } 
     } 

     public void setShouldRun(boolean shouldRun) { 
      synchronized (sync) { 
       this.shouldRun = shouldRun; 
      } 
     } 

    }