在 JLabel 中加载动画 GIF

问题描述:

我正在尝试在 JLabel 中加载动画 GIF.

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

虽然这有效:

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

另一方面,这不会,而且我不想从 URL 获取 GIF,因为我已经有了 GIF.加载结果只显示 GIF 的第一帧:

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.

谢谢!亚历克斯

您可以尝试像这样加载 GIF 文件:

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

或者使用 Test.class.getResouce() 如果您的上下文是静态的.

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