在Java 7中,透明GIF没有正确的动画

时间:2013-08-18 03:40:46

标签: animation java-7 transparent gif animated

所以,我遇到了一个程序问题。我有一个透明的GIF。动画正常工作,除了不是一次显示一个图像,它将图像堆叠在一起。我尝试重写ImageIcon类的paintIcon方法来清除画布,但这也不起作用。有什么想法吗? 我的代码:

    public class GifRunner extends JPanel {
      JLabel label;
      public GifRunner() {
        super();
        label = new JLabel();
        ImageIcon icon = new ImageIcon(getClass().getResource("/animation.gif");
        label.setIcon(icon);
        add(label);
      }
      public static void main(String[] args) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GifRunner panel = new GifRunner();
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
      }
    }

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

你可以覆盖ImageIcon的paintIcon函数并手动清除画布:

class ClearImageIcon extends ImageIcon{

    public ClearImageIcon(String filename){super(filename);}

    @Override
    public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setBackground(new Color(0,0,0,0));
        g2.clearRect(0, 0, getIconWidth(), getIconHeight());
        super.paintIcon(c, g2, x, y);
    }
}

它会很好地将每一帧画在屏幕上。

答案 1 :(得分:0)

对我来说很好......

Windows 7,Java 7.

enter image description here

Original

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class AnimatedGifTest {

  public static void main(String[] args) {
    new AnimatedGifTest();
  }

  public AnimatedGifTest() {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
          ex.printStackTrace();
        }

        JFrame frame = new JFrame("Testing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TestPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    });
  }

  public class TestPane extends JPanel {

    public TestPane() {
      setLayout(new GridBagLayout());
      ImageIcon image = new ImageIcon("C:\\Users\\swhitehead\\Documents\\My Dropbox\\Ponies\\appleture_animated_gif_by_inkwell_pony-d4uggao.gif");
      JLabel label = new JLabel(image);
      add(label);
    }        
  }      
}