用 JLabel 的 setIcon 方法替换后 Gif 不再动画

Gif no long animated after replacing with JLabel's setIcon method

我对 Java 和一般编程还是很陌生。我正在尝试使用 Swing 和以下代码显示 GIF:

    JPanel contentPane;
    JLabel imageLabel = new JLabel();

    public FrostyCanvas(String imageName) {
        try {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            contentPane = (JPanel) getContentPane();
            contentPane.setLayout(new BorderLayout());
            setSize(new Dimension(1600, 900));
            setTitle("FrostySpirit v1.1.1 (Beta) - FrostyCanvas");
            // add the image label
            ImageIcon ii = new ImageIcon(this.getClass().getResource(imageName));
            imageLabel.setIcon(ii);
            contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);
            // display target GIF
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

方法调用如下:(在不同的class)

FrostyCanvas FC = new FrostyCanvas("old.gif");

此时 GIF 动画。然后,我尝试使用以下方法将 GIF 替换为另一个 GIF:(与 ForstyCanvas(String imageName))

相同 class
public void changeGif(String imageName) throws IOException
    {
        Icon icon; File file;
        file = new File(imageName);
        icon = new ImageIcon(ImageIO.read(file));
        imageLabel.setIcon(icon);
    }

我使用以下代码在不同的 class 中调用上面的方法:

FC.changeGif("D:\new.gif")

图片替换成功。但是,现在它只显示 new.gif 的第一帧并且不再是动画。我怎样才能使新的 GIF 动起来?

ImageIO 读取图像的方式是创建静态图像。要做的事情是使用 ImageIcon 的加载程序。

ImageIcon replacement = new ImageIcon(file.toURI().toURL());

这样您就可以使用与资源相同的方法来构建图像图标 / url。