Loading animated GIF in JLabel weirdness

2019-02-17 04:42发布

I'm trying to load an animated GIF in a JLabel.

While this works:

URL urlsd;
try {
    urlsd = new URL("http://pscode.org/media/starzoom-thumb.gif");
    ImageIcon imageIcon = new ImageIcon(urlsd); 
    JLabel progress = new JLabel(imageIcon);    
    progress.setBounds(5, 20, 66, 66);
    contentPane.add(progress);
} catch (MalformedURLException e) {
    e.printStackTrace();
}

This, on the other hand, does not, and I don't want to get the GIF from an URL, since I already have the GIF. Result of loading this shows only the first frame of the GIF:

try {   
    ImageIcon imageIcon = new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("res/images/progress_indicator.gif")));

    JLabel progress = new JLabel(imageIcon);
    imageIcon.setImageObserver(progress);
    progress.setBounds(5, 20, 66, 66);
    contentPane.add(progress);
} catch (MalformedURLException e) {

    e.printStackTrace();
}

I guess there must be a reason for this, but I cannot find it.

Thanks! Alex

3条回答
叛逆
2楼-- · 2019-02-17 05:30

Below code worked for me, it will show the animation instead of first frame of the image.

public class Test extends JPanel {
    public Test() {
        ImageIcon yyyyIcon = new ImageIcon(xxx.class.getClassLoader().getResource("yyyy.gif"));
        connectionLabel.setIcon(yyyy);   
    }
}
查看更多
forever°为你锁心
3楼-- · 2019-02-17 05:34

So there is also a simpler way of doing it. The following line is how I did it.

this.setContentPane(new JLabel(new ImageIcon("Path To Gif File")));
查看更多
Viruses.
4楼-- · 2019-02-17 05:36

You can try loading your GIF file like that:

public class Test extends JPanel {
    public Test() {
        ImageIcon imageIcon =
          new ImageIcon(Test.this.getClass().getResource("starzoom-thumb.gif"));
    }
}

Or using Test.class.getResouce() if your context is static.

查看更多
登录 后发表回答