0

我使用 Swing.Timer 来减慢我的动画速度。但是,我想暂停当前的执行,直到 Timer 线程完成。我怎么做?Timer 会产生一个对原始线程不响应的新线程。这是一个演示的示例程序。

public class TimerFrame extends JFrame
{
  public static void main(String[] args)
  {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run()
      {
        TimerFrame frame = new TimerFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        TimeListener listener = new TimeListener();
        Timer timer = new Timer(1000, listener);
        timer.start();
        System.out.println("Timer running: " + timer);

        while (!timer.isRunning()) {
          System.out.println("Timer not running: " + timer);
          JOptionPane.showMessageDialog(null, "Quit program?");
          Calendar cal = Calendar.getInstance();
          System.out.println("main pgm: " + cal.getTimeInMillis());
        }
        System.exit(0);
      }
    });
  }
}

class TimeListener implements ActionListener
{
  static int _counter;

  public TimeListener()
  {
    _counter = 1;
  }

  @Override
  public void actionPerformed(ActionEvent e)
  {
    if (_counter <= 3) {
      String msg = "Timer: Counter = " + _counter + " " + e.getWhen();
      JOptionPane.showMessageDialog(null, msg);
      System.out.println(msg);
      _counter++;
    }

    else {
      Timer timer = (Timer) e.getSource();
      timer.stop();
      if (timer.isRunning()) {
        System.out.println("Timer.aP is still running after a stop request");
      }
      else {
        System.out.println("Timer.aP just stopped timer");
      }
    }
  }

}

请注意,即使 actionPerformed 停止计时器,计时器也会继续运行。在三个 OptionPane 出现后,程序永远不会退出。我预计当计时器完成时 isRunnable() 测试将是错误的。输出是

Timer running: javax.swing.Timer@2eb9b326
Timer: Counter = 1 1606837382597
Timer: Counter = 2 1606837385600
Timer: Counter = 3 1606837386601
Timer.aP just stopped timer
4

1 回答 1

1

我写了几个测试程序并找到了一种方法:在计时器停止时将一个标志放入 Listener 类中,并使用一个 getter 来返回标志的状态。调用程序循环直到计时器完成。这是监听器代码。

class TimeListener implements ActionListener
{
  static int _counter;
  boolean _endTimer;

  public TimeListener()
  {
    _counter = 1;
    _endTimer = false;
  }

  boolean isTimerDone()
  {
    return _endTimer;
  }


  @Override
  public void actionPerformed(ActionEvent e)
  {
    if (_counter <= 3) {
      String msg = "Timer: Counter = " + _counter + " " + e.getWhen();
      JOptionPane.showMessageDialog(null, msg);
      System.out.println(msg);
      _counter++;
    }

    else {
      Timer timer = (Timer) e.getSource();
      timer.stop();
      _endTimer = true;
    }
  }
}

在调用程序(等待计时器结束的程序)中,使用循环检查直到计时器完成:

TimeListener listener = new TimeListener();
Timer timer = new Timer(1000, listener);
timer.start();

// Wait until the timer completes
while (listener.isTimerDone());

// continue code here...
于 2020-12-01T16:44:21.733 回答