如何暂停主swing线程直到swing计时器完成?

j13ufse2  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(378)

我使用swing.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()测试为false。输出为

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

t1qtbnec1#

我编写了一些测试程序并找到了一种方法:当计时器停止时,将一个标志放入listener类中为true,并使用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...

相关问题