Loading animated GIF in JLabel weirdness

大憨熊 提交于 2019-12-01 02:53:59

问题


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


回答1:


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.




回答2:


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);   
    }
}



回答3:


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")));


来源:https://stackoverflow.com/questions/10622303/loading-animated-gif-in-jlabel-weirdness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!