0

I'm trying to get a gif to restart from the start midway through its animation when a button is pressed. How do I do this?

I've tried these methods:

lblDeath.setIcon(new ImageIcon(MainGame.class.getResource("/azzets/blank.png")));
lblDeath.setIcon(new ImageIcon(MainGame.class.getResource("/azzets/3 Seconds.gif")));
lblDeath.setVisible(false);
lblDeath.setIcon(new ImageIcon(MainGame.class.getResource("/azzets/3 Seconds.gif")));
lblDeath.setVisible(true);

(3 seconds gif is the one I'm trying to get to restart)

Thanks.

earandap
  • 1,446
  • 1
  • 13
  • 22
lewbisherr
  • 11
  • 1
  • 1
    Try using [`flush`](https://docs.oracle.com/javase/8/docs/api/java/awt/Image.html#flush--) on the `Image` of the `ImageIcon`. However you might want to be carefull with this if you use the same image multiple times, as mentioned [`here`](https://stackoverflow.com/questions/11745804/multiple-instances-of-the-same-animated-gif-in-a-canvas-java). – second Dec 17 '19 at 13:08

1 Answers1

0

Indeed, as mentioned in comment section you can use flush() to the icon image of the label:

ImageIcon icon = (ImageIcon) gifLabel.getIcon();
Image img = icon.getImage();
ImageIcon newIcon = new ImageIcon(img);
img.flush();
gifLabel.setIcon(newIcon);
George Z.
  • 6,643
  • 4
  • 27
  • 47