Show animated GIF
Asked Answered
H

11

37

How do you display an animated GIF in a Java application?

Hematite answered 29/5, 2010 at 13:29 Comment(0)
A
31

Using Swing you could simply use a JLabel:

public static void main(String[] args) throws MalformedURLException {
    URL url = new URL("<url_to_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);
}
Airliah answered 29/5, 2010 at 13:32 Comment(4)
For some reason, if you get your ImageIcon object with something like this Icon icon = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("iconasresource.gif"))); your GIF won't get animatedInerrant
Indeed, creating an ImageIcon with ImageIO.read does not animate the gif for some reason. Maybe obvious, but you can get the URL of the resource with: URL url = getClass().getResource("/img.gif");.Luxor
This is a horrid API... Was trying to figure out why the GIF wasn't animating. Couldn't find ANYTHING online until I came across the comment about ImageIO. Unbelievable.Reasonless
@Airliah how do you change the size and location of the gif? I am creating a video game and I want the gif to follow the player.Reynalda
T
5

check it out:

http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html#getresource

Theatricalize answered 29/5, 2010 at 13:36 Comment(0)
H
5

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);
Hairraising answered 4/11, 2014 at 22:25 Comment(1)
This is exactly what does not work for me. The image is loaded, but only the first frame is shown, no animation.Yen
B
4

This work for me!

public void showLoader(){
        URL url = this.getClass().getResource("images/ajax-loader.gif");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);
        frameLoader.setUndecorated(true);
        frameLoader.getContentPane().add(label);
        frameLoader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLoader.pack();
        frameLoader.setLocationRelativeTo(null);
        frameLoader.setVisible(true);
    }
Beitnes answered 22/2, 2016 at 19:10 Comment(1)
It is good to add a some explanation about your code. How is it different, why doe it work. Thanks (moderator).Geometrize
P
3

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) {
            }
Pekoe answered 2/2, 2017 at 16:58 Comment(0)
H
1

Fast and easy code:

Icon icon = new ImageIcon("src/image.gif");
JLabel label = new JLabel();

label.setIcon(icon);

Don't forget to have the JFrame visible and sized.

Hamsun answered 20/12, 2021 at 23:0 Comment(0)
C
0
//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);
   }
}
Christoper answered 29/12, 2017 at 18:59 Comment(0)
U
0

I wanted to put the .gif file in a GUI but displayed with other elements. And the .gif file would be taken from the java project and not from an URL.

1 - Top of the interface would be a list of elements where we can choose one

2 - Center would be the animated GIF

3 - Bottom would display the element chosen from the list

Here is my code (I need 2 java files, the first (Interf.java) calls the second (Display.java)):

1 - Interf.java

public class Interface_for {

    public static void main(String[] args) {

        Display Fr = new Display();

    }
}

2 - Display.java

INFOS: Be shure to create a new source folder (NEW > source folder) in your java project and put the .gif inside for it to be seen as a file.

I get the gif file with the code below, so I can it export it in a jar project(it's then animated).

URL url = getClass().getClassLoader().getResource("fire.gif");

  public class Display extends JFrame {
  private JPanel container = new JPanel();
  private JComboBox combo = new JComboBox();
  private JLabel label = new JLabel("A list");
  private JLabel label_2 = new JLabel ("Selection");

  public Display(){
    this.setTitle("Animation");
    this.setSize(400, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    container.setLayout(new BorderLayout());
    combo.setPreferredSize(new Dimension(190, 20));
    //We create te list of elements for the top of the GUI
    String[] tab = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
    combo = new JComboBox(tab);

    //Listener for the selected option
    combo.addActionListener(new ItemAction());

    //We add elements from the top of the interface
    JPanel top = new JPanel();
    top.add(label);
    top.add(combo);
    container.add(top, BorderLayout.NORTH);

    //We add elements from the center of the interface
    URL url = getClass().getClassLoader().getResource("fire.gif");
    Icon icon = new ImageIcon(url);
    JLabel center = new JLabel(icon);
    container.add(center, BorderLayout.CENTER);

    //We add elements from the bottom of the interface
    JPanel down = new JPanel();
    down.add(label_2);
    container.add(down,BorderLayout.SOUTH);

    this.setContentPane(container);
    this.setVisible(true);
    this.setResizable(false);
  }
  class ItemAction implements ActionListener{
      public void actionPerformed(ActionEvent e){
          label_2.setText("Chosen option: "+combo.getSelectedItem().toString());
      }
  }
}
Utley answered 15/2, 2018 at 14:48 Comment(0)
W
0
JLabel mainLabel = new JLabel();
FileChooser chooser = new FileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image", "png", "jpg", "gif");
chooser.setFileFilter(filter);
chooser.setDialogTitle(Lang.T("Open Image") + "...");
int returnVal = chooser.showOpenDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
    URL url;
    try {
        url = new URL("file:" + chooser.getSelectedFile().getPath());
    } catch (Exception e) {
        url = null;
    }

    Icon icon = new ImageIcon(url);
    mainLabel.setIcon(icon);
}

Use "file:" for URL

Waggon answered 13/3, 2021 at 12:7 Comment(0)
C
-1

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

Comatose answered 9/1, 2019 at 21:36 Comment(0)
L
-2
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);
    }
}
Lynettalynette answered 1/5, 2015 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.