将JAR文件中的gif动画加载到ImageIcon中
时间:2020-03-06 14:52:47 来源:igfitidea点击:
我正在尝试从jar文件中存储的动画gif创建ImageIcon。
ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
图像加载,但仅加载动画gif的第一帧。动画不播放。
如果我从文件系统上的文件中加载动画gif,一切都会按预期进行。动画在所有帧中播放。所以这有效:
ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
如何从jar文件将动画gif加载到ImageIcon中?
编辑:这是一个完整的测试用例,为什么不显示动画?
import javax.imageio.ImageIO; import javax.swing.*; public class AnimationTest extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { AnimationTest test = new AnimationTest(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }); } public AnimationTest() { super(); try { JLabel label = new JLabel(); ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif"))); label.setIcon(imageIcon); imageIcon.setImageObserver(label); add(label); pack(); } catch (Exception e) { e.printStackTrace(); } } }
解决方案
我们必须使用getClass()。getResource(imgName);获取图像文件的URL。从Real的HowTo中查阅本教程。
编辑:加载图像后,我们必须设置ImageObserver属性以使动画运行。