我試圖創建存儲在一個jar文件中的gif動畫一個的ImageIcon。加載動畫從JAR文件GIF到ImageIcon的
ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
圖像加載,但只是動畫gif的第一幀。動畫不播放。
如果我從文件系統中的文件加載gif動畫,按預期工作的一切。動畫播放所有幀。所以這個作品:
ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
如何從jar文件加載動畫gif到ImageIcon中?
編輯:這裏是,爲什麼不這樣顯示的動畫完整的測試案例?
import javax.imageio.ImageIO;
import javax.swing.*;
public class AnimationTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AnimationTest test = new AnimationTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
});
}
public AnimationTest() {
super();
try {
JLabel label = new JLabel();
ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
label.setIcon(imageIcon);
imageIcon.setImageObserver(label);
add(label);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我使用代碼的第一部分從jar文件加載png圖像就好了。而GIF加載 - 它只是沒有動畫。 – 2008-09-29 15:34:30
我現在看到你的問題。查看我的編輯瞭解更多詳情。 – 2008-09-29 16:19:25
設置ImageObserver在我的情況下沒有幫助。看來ImageIO沒有正確讀取動畫GIF。如果我爲ImageIcon使用不同的構造函數,它將起作用。我用一個完整的代碼示例更新了這個問題。你需要在你的類路徑中使用animated.gif。 – 2008-09-29 17:41:48