JLabel two = new JLabel();
ImageIcon jaina= new ImageIcon("images/jaina.gif");
two.setBounds(0,0,300,300);
two.setIcon(jaina);
then i added the Label to my panel, it plays only once
JLabel two = new JLabel();
ImageIcon jaina= new ImageIcon("images/jaina.gif");
two.setBounds(0,0,300,300);
two.setIcon(jaina);
then i added the Label to my panel, it plays only once
If your gif is not set to loop, the correct solution is to modify the gif to have it loop.
Out of curiosity I mocked up this example. What if I want to animate a gif independent of its animation settings.
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.EventQueue;
public class GifLabel{
public static void startGui( List<ImageIcon> imgs){
JFrame frame = new JFrame("animated gif");
JLabel label = new JLabel( );
frame.add(label);
label.setIcon(imgs.get(0));
Timer t = new Timer( 30, new ActionListener(){
int i = 0;
@Override
public void actionPerformed( ActionEvent evt ){
label.setIcon ( imgs.get(i) );
i = (i+1)%imgs.size();
}
});
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
t.start();
}
public static void main(String[] args) throws Exception{
ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next();
reader.setInput( new FileImageInputStream( new File("images/jaina.gif")));
int n = reader.getNumImages( true );
List<ImageIcon> imgs = new ArrayList<>();
for(int i = 0; i<n; i++){
imgs.add( new ImageIcon(reader.read(i)) );
}
EventQueue.invokeLater( ()->{
startGui(imgs);
});
}
}
This is way more fragile than just making sure the GIF is the correct format. Also way more code, considering the original new ImageIcon("...");
handles everything.