Java 在JLabel-weirdness中加载动画GIF

Java 在JLabel-weirdness中加载动画GIF,java,swing,jlabel,animated-gif,Java,Swing,Jlabel,Animated Gif,我正在尝试在JLabel中加载动画GIF 虽然这样做有效: 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);

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

虽然这样做有效:

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的第一帧:

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();
}
我想这一定是有原因的,但我找不到原因

谢谢!
Alex

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

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

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

下面的代码适用于我,它将显示动画而不是图像的第一帧

public class Test extends JPanel {
    public Test() {
        ImageIcon yyyyIcon = new ImageIcon(xxx.class.getClassLoader().getResource("yyyy.gif"));
        connectionLabel.setIcon(yyyy);   
    }
}

因此,还有一种更简单的方法。下面一行是我如何做到的

this.setContentPane(new JLabel(new ImageIcon("Path To Gif File")));

ClassLoader确实不是访问
应用程序资源的方式,请尝试此链接,希望这可能会有所帮助,为什么不使用ClassLoader,如本文所述,它声明“所有类加载器将首先搜索作为系统资源的资源,类似于类文件的搜索方式”@AlejandroVK:对于一个工作示例,请参考这个Ahha,我将使用这个答案,
getClass()。getResource(…)
是解决方法:-)我怀疑这就是答案。
getResourceAsStream
返回的流会发生奇怪的事情(例如声音应用程序。可能会失败,因为流“无法重新定位”)。但是提供一个
URL
,它工作得很好。谢谢,它工作得很好,尽管我必须检查它,以便意识到我必须首先包含一个斜杠…使用GetSystemResourcesStream方法不需要这样做:请注意,如果您的GIF位于
myProject/src/main/resources/icons/myGif.GIF
,您应该通过
“icons/myGif.gif
getResource
。这与
getResourceAsStream
的用法不同,在这里您必须在文件路径前面加一个斜杠:
“/icons/myGif.gif
。请添加一些说明。