Java动画GIF而不使用JLabel
问题描述:
有没有办法在不使用JLabel的情况下在Java中显示动画GIF图像?我正在尝试在游戏中实现一些GIFS,并且想要绘制它们而不需要混淆JComponents。图像观察者会工作吗?我运气不好吗?
Is there a way to display an animated GIF image in Java without using a JLabel? I'm trying to implement some GIFS in a game and would like to just paint them without needing to mess with JComponents. Would an image observer work? Am I out of luck?
答
以下在不使用JLabel的情况下在JPanel中显示图像:
Following shows a image in JPanel without using JLabel:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ImagePanel extends JPanel
{
Image image;
public ImagePanel()
{
image = Toolkit.getDefaultToolkit().createImage("e:/java/spin.gif");
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
JFrame frame = new JFrame();
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}