您好,我在JFrame中有一个gif。这一切都很好,除了gif第一次冻结,好像它是一个jpeg或png。
此外,stackoverflow告诉我我需要添加更多详细信息,即使我已经添加了所有必需的详细信息以便说明我的问题,所以请随意忽略这一点。
以下是代码:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class LoadImageApp extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, this);
}
public LoadImageApp() {
try {
img = ImageIO.read(new File("spooky.gif"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new LoadImageApp());
f.pack();
f.setVisible(true);
}
}
答案 0 :(得分:4)
我很确定ImageIO
GIF动画有一些问题。
尝试使用JLabel
和图标,如下所示:
Icon icon = new ImageIcon(filename);
JLabel gif = new JLabel(icon);
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.getContentPane().add(gif);
f.pack();
f.setVisible(true);
答案 1 :(得分:3)
如上所述,ImageIO
无法正确加载动画GIF的所有帧。但其中一个Toolkit
方法会。 E.G。
import java.awt.*;
import javax.swing.*;
import java.net.URL;
// Ach AWT!
//public class LoadImageApp extends Component {
public class LoadImageApp extends JPanel {
Image img;
// should be paintComponent for a JComponent
//public void paint(Graphics g) {
public void paintComponent(Graphics g) {
super.paintComponent(g); // call super method first
g.drawImage(img, 0, 0, this);
}
public LoadImageApp() {
setBackground(Color.BLUE.darker().darker());
try {
URL url = new URL("http://i.stack.imgur.com/OtTIY.gif");
// as mentioned, ImageIO will not load animated GIFs correctly.
//img = ImageIO.read(url));
// but the toolkit method will, OTOH..
img = Toolkit.getDefaultToolkit().createImage(url);
// ..we need a MediaTracker
MediaTracker mt = new MediaTracker(this);
mt.addImage(img, 0);
mt.waitForAll();
} catch (Exception e) {
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100, 100);
} else {
return new Dimension(img.getWidth(this), img.getHeight(this));
}
}
public static void main(String[] args) {
// should be donw on the EDT - BNI
JFrame f = new JFrame("Load Image Sample");
f.add(new LoadImageApp());
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
有关进一步的讨论,请参阅Show an animated BG in Swing。