Java延迟重绘帧

时间:2017-12-01 08:00:46

标签: java swing timer

我正在尝试为我的16个拼图应用程序的解决方案设置动画,我对如何使用Timer类的建议持开放态度。目前,动画发生得非常快,只显示最终状态。我尝试将延迟增加到3000毫秒,但结果是一样的。

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();
    }
}

1 个答案:

答案 0 :(得分:1)

您可能不想在循环的每次迭代中创建不同的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<>();
相关问题