[英]How to pause program execution without blocking a Timer (Java Swing)?
我有一個計時器,當游戲事件發生時,它會在屏幕上顯示動畫。 我想要做的是讓主動執行暫停,直到這個動畫結束,但我嘗試的一切似乎阻止了Timer的運行。 我已經嘗試使用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對象中的Timer和偵聽器:
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()中注釋掉睡眠/等待行,則動畫會運行,但程序不會暫停。
一種方法是在動畫進行時顯示模態對話框 。 作為討論在這里 ,用戶交互將被取消贖回權,但在應對背景GUI更新javax.swing.Timer
仍將繼續。 您可以讓用戶隨時關閉該對話框,如圖所示這里 ,但你可能要放棄在該點的動畫。
不需要用戶輸入。
您可以通過在動畫開始后輸入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 ();
…
}
}
你可以試試這個:
timer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// your code
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.