我正在尝试为我的 16 个谜题应用程序的解决方案制作动画,并且我愿意接受有关如何使用 Timer 类的建议。目前动画发生得非常快,并且只显示最终状态。我尝试将延迟增加到 3000ms,但结果是一样的。
public void animateSolution(Node node)
{
Stack<Node> solution = new Stack<>();
while (node != null)
{
solution.push(node);
node = node.getParent();
}
while (!solution.isEmpty())
{
Node current = solution.pop();
Timer timer = new Timer(750, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
moveBuilder(current);
repaint();
}
});
timer.setRepeats(false);
timer.start();
}
}
最佳答案
您可能不想在循环的每次迭代中创建一个不同的Timer
。
考虑使用单个Timer
并摆脱第二个while
循环,例如:
Timer timer = new Timer(750, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(!solution.isEmpty()){
Node current = solution.pop();
moveBuilder(current);
repaint();
}
}
});
timer.setRepeats(true);
timer.start();
请注意,要使该匿名类与 solution
一起使用,您必须将 solution
声明为 final
:
final Stack<Node> solution = new Stack<>();
关于Java延迟帧重画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47588964/