Why aren't gif animations animated when used in paintComponent ()?

I use paintComponent() to draw a gif-animated image in the JPanel backgound. It displays a gif, but does not animate. I am using java 1.5 and I know that I can use the icon shortcut.

Does anyone know why and how to fix it?

  private static class CirclePanel extends JPanel { ImageIcon imageIcon = new ImageIcon(BarcodeModel.class.getResource("verify.gif")); Point point = f.getLocation(); protected void paintComponent(Graphics g) { Graphics gc = g.create(); Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); g2d.setColor(Color.BLUE); g2d.drawImage(imageIcon.getImage(), getWidth() / 2, getHeight() / 2, null); g2d.drawRect(0, 0, getWidth(), getHeight()); g2d.setStroke(new BasicStroke(10f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER)); g2d.setFont(g.getFont().deriveFont(Font.BOLD | Font.ITALIC,15f)); g2d.drawString("Wait Please ...",getWidth()/2-imageIcon.getIconHeight()/3,getHeight()/2+imageIcon.getIconHeight()+15); g2d.dispose(); } 

This is a gif image.
enter image description here

Edited: just add an image observer to the g2d.drawImage () method.

  g2d.drawImage(imageIcon.getImage(), getWidth() / 2, getHeight() / 2, this); 
+7
source share
2 answers

The reason is that the standard Java ImageIO API only loads the first gif image. How to fix? Google for Gif Loader for Java, which uploads every gif image. Then you should draw the right image at the right time. An alternative way would be to have different png files representing one frame of animation each time.

Update: Well ... Actually, after some research, it looks like you did, it actually loads all the frames of the animated gif. The reason for this is that the ImageIcon getImage() method always returns the first image.

To fix this, you can try this (I'm not sure if this will work ...)

Instead of Grahpics.drawImage() use ImageIcon.paintIcon() . Like this:

 imageIcon.paintIcon(this, g2d, getWidth() / 2 - imageIcon.getIconWidth() / 2, getHeight() / 2); 
+9
source

The image observer will take care of this. You should just look at the observer at g2d.drawImage(); as shown below.

 g2d.drawImage(imageIcon.getImage(), getWidth() / 2, getHeight() / 2, this); 

In my case of 'this', refer to the CirclePanel that extends JPanel, it can be any thing, for example, if you use gif as an icon for a button, you should use the button as an image observer.

+4
source

All Articles