Java延迟帧重画

标签 java swing timer

我正在尝试为我的 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/

相关文章:

java - 无法以联觉方式绘制像素、Pi 数

java - 将 Observable 转为 ObservableValue/Binding/EventStream 的最有效方法?

iphone - 每个细节 View Controller 一个计时器

ios - 每个 CollectionView Cell 都有独特的计时器

java - 在 Java 中通过 GridLauncherV3 启动 Selenium Grid

java - 使用其图形在另一个内部绘制控件

java - JPasswordField 编码输入

java - 在 Jfreechart 中自定义鼠标光标

java - 如何用Swing中的控件填充GridbagLayout的单元格?

python - 使用 threading.Timer 时 Ctrl-C 不起作用