有没有办法在不使用 JLabel 的情况下在 Java 中显示动画 GIF 图像?我正在尝试在游戏中实现一些 GIFS,并且只想绘制它们而无需弄乱 JComponents。图像观察员会工作吗?我倒霉了吗?

最佳答案

下面显示了 JPanel 中不使用 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);
      }
    });
  }
}

关于不使用 JLabel 的 Java 动画 GIF,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5613120/

10-12 12:43
查看更多