在JLabel中显示来自URL的动画GIF

4

有没有办法像JPEG或PNG图像一样在JLabel中显示动画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个回答

5

请使用:

ImageIcon icon = new ImageIcon(url);  

请参见在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接