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.

Shinmera
  • 310
  • 1
  • 6

1 Answers1

0

this http://download.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html contains GradientPaint, that's is similair as add Image or ImageIcon

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I fail to see how this solves my problem with the animation. Care to elaborate? – Shinmera May 07 '11 at 18:01
  • create a Window (JFrame http://download.oracle.com/javase/tutorial/uiswing/components/toplevel.html), put here JLabel http://download.oracle.com/javase/tutorial/uiswing/components/label.html with BorderLayout.Center http://download.oracle.com/javase/tutorial/uiswing/layout/border.html and to tha JLabel put Image or ImageIcon http://download.oracle.com/javase/tutorial/uiswing/components/icon.html – mKorbel May 07 '11 at 18:10
  • That's what my code is already doing, without the transparency. – Shinmera May 07 '11 at 18:35
  • ok then compare example from translucency with your code, add missed statements and methods :-) – mKorbel May 07 '11 at 19:32