Java animated GIF example

Someone asked yesterday if you can use animated GIF images in Java applications using the JFC/Swing toolkit. That's something I hadn't tried with Java and Swing before, so I wrote a quick test program, and sure enough they work.

I just load an animated GIF as an ImageIcon, then put it on a JLabel and display it on a JFrame, and the animation starts right up. Note that I'm using a Java/JDK 1.4.x release.

We were discussing this within the context of one of my test jobs crashing, and how happy I was that I could make the job crash now that we had transactions enabled on the database server to keep my job from becoming corrupt. So I joked that I felt like dancing around like Snoopy, and sure enough someone had an animated GIF of Snoopy dancing. He then asked if I could put that in the Swing application we are developing, which led me to create this sample code.

Here's a static image of what my Swing program looks like when it's running on a Windows 2000 PC:

And here's my example source code:

  * A sample program showing how to use an animated gif image
  * in a Java Swing application.

package giftest;

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

public class MainFrame extends JFrame {
    JPanel contentPane;
    JLabel imageLabel = new JLabel();
    JLabel headerLabel = new JLabel();

    public MainFrame() {
        try {
            contentPane = (JPanel) getContentPane();
            contentPane.setLayout(new BorderLayout());
            setSize(new Dimension(400, 300));
            setTitle("Your Job Crashed!");
            // add the header label
            headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
            headerLabel.setText("   Your job crashed during the save process!");
            contentPane.add(headerLabel, java.awt.BorderLayout.NORTH);
            // add the image label
            ImageIcon ii = new ImageIcon(this.getClass().getResource(
            contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);
            // show it
        } catch (Exception exception) {

    public static void main(String[] args) {
        new MainFrame();