4

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);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

5

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
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433