gpt4 book ai didi

java - 如何在不阻塞计时器(Java Swing)的情况下暂停程序执行?

转载 作者:行者123 更新时间:2023-11-29 04:40:31 24 4
gpt4 key购买 nike

我有一个计时器,当游戏事件发生时,它会在屏幕上显示动画。我想要做的是让主执行暂停,直到这个动画结束,但我尝试的一切似乎都阻止了计时器运行。我试过使用 Thread.sleep() 并在锁对象上调用 wait() 和 notify(),但结果相同。 Timer 监听器的 actionPerformed() 永远不会被调用。

此代码设置计时器:

protected void showMovingEffect(int steps, Direction dir, AnimatedImageSet imgs) {
effectsPane.runAnimation(imgs, dir, steps);
waiting = true;
while (waiting) {
synchronized(animationWaitLock) {
try {
animationWaitLock.wait();
} catch (InterruptedException e) {}
}
}
}

以及 EffectsPane 对象中的定时器和监听器:

private void runAnimation(AnimatedImageSet ais, Direction dir, int iters) {
System.out.println("run");
imgs = ais;
top = 0;
left = 0;
topStep = dir.getRowIncrement() * 10;
leftStep = dir.getColIncrement() * 10;
iterations = iters;
index = 0;
active = true;
timer.start();
}

public void actionPerformed(ActionEvent e) {
System.out.println(index);
top += topStep;
left += leftStep;
index++;
currentImage = imgs.getImage(index);
repaint();
if (index == iterations) {
active = false;
timer.stop();
synchronized(animationWaitLock) {
animationWaitLock.notify();
}
waiting = false;
}
}

在 actionPerformed() 开始时的 System.out.println 调用从未被调用,因此 wait() 调用也暂停了 Timer,或者有什么东西阻止了它。如果我在 showMovingEffect() 中注释掉 sleep /等待线,动画会运行,但程序不会暂停。

最佳答案

一种方法是显示 modal dialog动画进行时。正如所讨论的here ,用户交互将被取消,但后台 GUI 会更新以响应 javax.swing.Timer将继续。您可以允许用户随时关闭对话框,如图所示 here ,但此时您可能想放弃动画。

no input from the user is needed.

您可以通过输入 SecondaryLoop 来阻止用户交互而不显示对话框。动画开始后。

SecondaryLoop loop = Toolkit.getDefaultToolkit()
.getSystemEventQueue().createSecondaryLoop();
timer.start();
loop.enter();

当动画结束时,exit() SecondaryLoop:

public void actionPerformed(ActionEvent e) {

if (index == iterations) {
timer.stop();
loop.exit ();

}
}

关于java - 如何在不阻塞计时器(Java Swing)的情况下暂停程序执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com