views:

2429

answers:

1

I'm trying to create a ImageIcon from a animated gif stored in a jar file.

ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));

The image loads, but only the first frame of the animated gif. The animation does not play.

If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:

ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");

How can I load an animated gif into an ImageIcon from a jar file?

EDIT: Here is a complete test case, why doesn't this display the animation?

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();
        }
    }
}
+2  A: 

You have to use getClass().getResource(imgName); to get a URL to the image file. Check out this tutorial from Real's HowTo.

EDIT: Once the image is loaded you have to set the ImageObserver property to get the animation to run.

Bill the Lizard
I load png images just fine from the jar file using the first section of code. And the gif loads - it's just not animated.
Steve K
I see your problem now. See my edit for more details.
Bill the Lizard
setting the ImageObserver did not help in my case. It seems that ImageIO isn't reading the animated gif properly. If I use a different constructor for the ImageIcon, it works. I updated the question with a complete code example. You'll need an animated.gif in your classpath.
Steve K