【问题标题】:Display animated .gif from URL in JLabel在 JLabel 中显示来自 URL 的动画 .gif
【发布时间】:2015-09-13 02:55:52
【问题描述】:

有没有办法像 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);

【问题讨论】:

    标签: java image swing jlabel gif


    【解决方案1】:

    改为使用:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-09-15
      • 2019-08-03
      • 2014-05-06
      • 2014-10-14
      • 2012-05-24
      • 2011-02-25
      • 2012-09-15
      • 2013-03-14
      • 1970-01-01
      相关资源
      最近更新 更多