How do you display an animated GIF in a Java application?
I came here searching for the same answer, but based on the top answers, I came up with an easier code. Hope this will help future searches.
Icon icon = new ImageIcon("src/path.gif");
try {
mainframe.setContentPane(new JLabel(icon));
} catch (Exception e) {
}
Try this:
// I suppose you have already set your JFrame
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);
Found on this tutorial on how to display animated gif in java
Or live on youtube : https://youtu.be/_NEnhm9mgdE
//Class Name
public class ClassName {
//Make it runnable
public static void main(String args[]) throws MalformedURLException{
//Get the URL
URL img = this.getClass().getResource("src/Name.gif");
//Make it to a Icon
Icon icon = new ImageIcon(img);
//Make a new JLabel that shows "icon"
JLabel Gif = new JLabel(icon);
//Make a new Window
JFrame main = new JFrame("gif");
//adds the JLabel to the Window
main.getContentPane().add(Gif);
//Shows where and how big the Window is
main.setBounds(x, y, H, W);
//set the Default Close Operation to Exit everything on Close
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Open the Window
main.setVisible(true);
}
}
Using swing you could simply use a JLabel
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("<URL to your Animated GIF>");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
For loading animated gifs stored in a source package (in the source code), this worked for me:
URL url = MyClass.class.getResource("/res/images/animated.gif");
ImageIcon imageIcon = new ImageIcon(url);
JLabel label = new JLabel(imageIcon);
public class aiubMain {
public static void main(String args[]) throws MalformedURLException{
//home frame = new home();
java.net.URL imgUrl2 = home.class.getResource("Campus.gif");
Icon icon = new ImageIcon(imgUrl2);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}