在JLabel中显示来自URL的动画.gif文件

时间:2015-06-26 08:21:21

标签: java image swing jlabel gif

有没有办法在JLabel中像JPEG或PNG图像一样显示动画GIF图像?我想从URL加载动画GIF,以便在标签中显示它。

如果我尝试使用常见的静态图像方法,我只会收到GIF的第一帧......

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

ImageIcon icon = new ImageIcon(image); 

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

1 个答案:

答案 0 :(得分:5)

改为使用:

ImageIcon icon = new ImageIcon(url);  

另请参阅Show an animated BG in Swing了解更改的原因。

简而言之,使用ImageIO加载动画GIF将创建一个静态GIF(由动画的第一帧组成)。但是如果我们将URL传递给ImageIcon,它将正确加载动画的所有帧然后运行它们。

所以改变这个:

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

ImageIcon icon = new ImageIcon(image); 

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

对此:

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

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

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

甚至这个:

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