java 在 JLabel 中加载动画 GIF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10622303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading animated GIF in JLabel weirdness
提问by AlejandroVK
I'm trying to load an animated GIF in a JLabel.
我正在尝试在 JLabel 中加载动画 GIF。
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:
另一方面,这不会,而且我不想从 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();
}
I guess there must be a reason for this, but I cannot find it.
我想这一定是有原因的,但我找不到。
Thanks! Alex
谢谢!亚历克斯
回答by Xeon
You can try loading your GIF file like that:
您可以尝试像这样加载您的 GIF 文件:
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.
或者Test.class.getResouce()
在您的上下文是静态的情况下使用。
回答by Naveen Kumar Pyla
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);
}
}
回答by Lucifer
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")));