Java动画GIF而不使用JLabel [英] Java animated GIF without using a JLabel

查看:94
本文介绍了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);
      }
    });
  }
}

这篇关于Java动画GIF而不使用JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆