簡體   English   中英

Java觸發ActionEvent

[英]Java Firing ActionEvent

我以前見過這樣的帖子,但是問題或答案不清楚,所以如果您以前聽過,請多多包涵。 我有一個計時器,我希望在計時器關閉時發生ActionEvent。 我不想使用javax.swing.Timer方法。 如何才能做到這一點? 沒有必要進行解釋,但這會有所幫助。 method 我正在尋找類似方法的東西

我的代碼:

/**
 * 
 * @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);

}

謝謝! 丹多18

在這里,您有一些簡單的計時器實現。 為什么您不檢查其他計時器的工作原理呢?

 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;
            }
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM