【问题标题】:Java Firing ActionEventJava 触发 ActionEvent
【发布时间】:2013-12-22 04:10:17
【问题描述】:

我以前看过这样的帖子,但问题或答案不清楚,如果你以前听过,请多多包涵。我有一个计时器,我希望在计时器关闭时发生一个 ActionEvent。我不想使用 javax.swing.Timer 方法。如何才能做到这一点?没有必要解释,但这会有所帮助。我正在寻找类似 ActionEvent.do() 方法

我的代码:

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

【问题讨论】:

  • “我以前也看到过这样的帖子,但问得不好” ...真是巧合...
  • 只需使用Timer。您的实现似乎是单线程的。
  • @SotiriosDelimanolis 我想知道一种不用定时器的方法。
  • I'm looking for something like an ActionEvent.do() method - 这是 Swing Timer 的工作方式。每当 Timer 触发时,它都会创建一个 ActionEvent,然后使用此 ActionEvent 调用 ActionListener 的 actionPeformed() 方法。
  • 为什么使用Swing Timer?

标签: java timer actionevent


【解决方案1】:

这里有一些简单的计时器实现。为什么你没有检查其他计时器的工作原理?

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

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多