简体   繁体   中英

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. I don't want to use the javax.swing.Timer method. 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

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

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM