我对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替换为另一种:(与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?
ImageIO读取图像的方式正在创建静态图像。要做的是使用ImageIcon的加载程序。
ImageIcon replacement = new ImageIcon(file.toURI().toURL());
那样,您将使用与资源/ URL相同的方法来构造图像图标。