Useful Java Code Snippets 7 - Animated GIF on JFrame

Hello everyone, today we are going to learn how to add GIF animations to JFrame and JPanel. In order to accomplish this, we are going to use ImageIcon class of the javax.swing.

Let's start with writing the class that we are going to use as a panel in our JFrame.;

* Author : Berk Soysal

package gifPlayer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class gifAnimated extends JPanel{

  private static final long serialVersionUID = 1L; // to avoid the warning
  private final int width = 640;
  private final int height = 480;
  private Image gifFile;
  public gifAnimated(){
    setPreferredSize(new Dimension(width, height));
 //Load the gif from the directory
  private void loadGif(){
   // file.gif is in the src folder
    ImageIcon intro = new ImageIcon(this.getClass().getResource("/file.gif"));
    gifFile = intro.getImage();
  public void paintComponent(Graphics g) {
    g.setColor(Color.BLACK); // set default color to black
    g.fillRect(0, 0, width, height);  // paint the background
    g.drawImage(gifFile, width/5, height/5, this);  //draw the animation to the panel

After writing our gifAnimated class, now it's time to code our main class..;

* Author : Berk Soysal

package gifPlayer;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class Main extends JFrame {

  private static final long serialVersionUID = -4562593047521834395L; // to avoid the warning

  public Main() {

    add(new gifAnimated());


    setTitle("Title of the JFRAME");

  public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
     public void run() {           

      JFrame myframe= new Main();



Please leave a comment if you have any questions or comments.

Continue Reading Useful Java Code Snippets 8 - File Finder in Java


Software Developer, Codemio Admin

Disqus Comments Loading..