I am 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);
It almost works. It displays animation smoothly and has transparency. The problem is that all frames of the animation overlap instead of receiving a cleared canvas and the current frame for each step of the frame. I assume that the JLabel canvas does not clear every step of the redraw. Does anyone know how I can fix this?
Edit: I understood the solution. I had to override the ImageIcon 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); } }
It paints beautifully every frame on the screen.
source share