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.

gifAnimated.java;

/**
* 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;
 
  //Constructor
  public gifAnimated(){
  
    setFocusable(true);
    setPreferredSize(new Dimension(width, height));
    loadGif();
  }
 
 //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();
  }
 
  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(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..

Main.java;
 

/**
* 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());

    setResizable(false);
    pack();

    setTitle("Title of the JFRAME");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }


  public static void main(String[] args) {

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

      JFrame myframe= new Main();

      myframe.setVisible(true);                
     }
   });
 }
}


Output: 





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

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

Author:

Software Developer, Codemio Admin

Disqus Comments Loading..