简体   繁体   English

Java触发ActionEvent

[英]Java Firing ActionEvent

I've seen posts like this before but the questions or the answers are unclear, so bear with me if you've heard this before. 我以前见过这样的帖子,但是问题或答案不清楚,所以如果您以前听过,请多多包涵。 I have a timer and I want an ActionEvent to occur when the timer is set off. 我有一个计时器,我希望在计时器关闭时发生ActionEvent。 I don't want to use the javax.swing.Timer method. 我不想使用javax.swing.Timer方法。 How can this be done? 如何才能做到这一点? It is not necessary to explain but that would be helpful. 没有必要进行解释,但这会有所帮助。 I'm looking for something like an ActionEvent.do() method 我正在寻找类似ActionEvent.do()方法的东西

My Code: 我的代码:

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

}

Thanks! 谢谢! Dando18 丹多18

Here you have some simple timer implementation. 在这里,您有一些简单的计时器实现。 Why you just didn't check how other timers work ? 为什么您不检查其他计时器的工作原理呢?

 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