Display animated .gif from URL in JLabel

1.6k views Asked by At

Is there any way to display an animated GIF image in a JLabel like a JPEG or PNG image? I would like to load an animated GIF from a URL to display it in a label.

If I try it with the common method of static images I just receive the first frame of the GIF...

url = new URL("http://example.gif");
image = ImageIO.read(url);

ImageIcon icon = new ImageIcon(image); 

picture = new JLabel();
picture.setIcon(icon);
1

There are 1 answers

0
Andrew Thompson On BEST ANSWER

Instead use:

ImageIcon icon = new ImageIcon(url);  

See also Show an animated BG in Swing for why that change works.

In a nutshell, loading an animated GIF using ImageIO will create a static GIF (consisting of the first frame of the animation). But if we pass the URL to the ImageIcon, it will correctly load all frames of the animation and then run them.


So change this:

url = new URL("http://example.gif");
image = ImageIO.read(url);

ImageIcon icon = new ImageIcon(image); 

picture = new JLabel();
picture.setIcon(icon);

To this:

url = new URL("http://example.gif");

ImageIcon icon = new ImageIcon(url); // load image direct from URL

picture = new JLabel(icon); // pass icon to constructor

Or even this:

url = new URL("http://example.gif");
picture = new JLabel(new ImageIcon(url)); // don't need a reference to the icon