5

I'm trying to display an animated gif on a transparent JDialog using a simple JLabel:

JDialog dialog = new JDialog();
AWTUtilities.setWindowOpaque(dialog,false);

JLabel label = new JLabel();
ImageIcon ii = new ImageIcon("animation.gif");
label.setIcon(ii);

JPanel panel = new JPanel();
panel.setBackground(new Color(0,0,0,0));
panel.add(label);
dialog.add(panel);

dialog.setVisible(true);

This almost works. It displays the animation smoothly and it does have transparency. The problem is that all the animation frames are overlaid instead of getting a cleared canvas and the current frame every frame step. I assume that the JLabel's canvas doesn't get cleared every repaint step. Does anyone know how I can fix this?

Edit: I figured out a solution. I had to override the ImageIcon's paintIcon function and manually clear the canvas:

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);
    }
}

this draws every frame nicely on to the screen.

4

1 に答える 1