我使用 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