替换为 JLabel 的 setIcon 方法后,Gif 不再有动画

问题描述 投票:0回答:1

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

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

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

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

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

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

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

图片替换成功。然而,现在它只显示 new.gif 的第一帧,并且不再是动画的。如何让新的GIF动起来?

java image swing jlabel animated-gif
1个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.