I have a gif Image being displayed on a JPanel in an endless Loop. Now I need to stop the animation after a random amount of Frames. In fact, I generate a random number that can be 0 or 1. Say the gif consists of 6 Frames. If the number is 0 I want to stop at the 3rd Frame, if it is 1 the animation should freeze at the 6th Frame.
To realize this I tried to use a Swing Timer which fires Events exactly when the next Frame comes. So if the Frames have a delay of 50 ms, I construct the Timer like
new Timer(50, this);
Sadly, this doesn't seem to work, in fact the Animation seems to be slower than the Timer. (I assume this has something to do with loading Times.) Anyway, i added some Code illustrating the Problem and (faily) Solution approach.
import java.awt.event.*;
import javax.swing.*;
public class GifTest extends JPanel implements ActionListener{
ImageIcon gif = new ImageIcon(GifTest.class.getResource("testgif.gif"));
JLabel label = new JLabel(gif);
Timer timer = new Timer(50, this);
int ctr;
public GifTest() {
add(label);
timer.setInitialDelay(0);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
ctr++;
if (ctr == 13){
timer.stop();
try {
Thread.sleep(1000);
} catch (InterruptedException i) {
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Gif Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GifTest());
frame.setSize(150,150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For the giftest.gif, it is a simple 6 Layers with the Numbers 1 to 6 on them, saved with a delay of 50ms.
I would be grateful for any help.
Ps: If it turns out that there is no elegant way to do this, it would also suffice to retrieve the Frame currently displayed. That way I could ask for it and stop when it's the 3rd (resp. 6th) Frame. Due to the task's context i would prefer a modified version of my solution though.