0

所以,我遇到了一个程序问题。我有一个透明的 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);
      }
    }

任何帮助将非常感激

4

2 回答 2

0

对我来说很好...

视窗 7,Java 7。

在此处输入图像描述

原来的

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);
    }        
  }      
}
于 2013-08-18T04:08:00.360 回答
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);
    }
}

它会将每一帧都很好地绘制到屏幕上。

于 2013-08-18T03:53:48.717 回答