Play a GIF Image on a JPanel without using URL (JAVA)

0

Good!

Look, I have a class called GIFPanel that inherits from the JPanel class

package Trivia;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

public class GIFPanel extends JPanel{
      private Image imagen;
      public GIFPanel(Image imagen){
          this.imagen = imagen;
      }

      @Override
      public void paintComponent(Graphics g){
          super.paintComponent(g);
          g.drawImage(imagen,0,0,getWidth(),getHeight(),this);
      }     
}

In my other class I believe it and I insert an image whose source was from a web address

Image img = Toolkit.getDefaultToolkit().getImage(new URL("https://media.giphy.com/media/l3q2XKiWAOl0qa1Tq/source.gif"));
menu = new GIFPanel(img);

Ok, it works correctly, the gif plays back even with the generated JAR .... but ... it's not really what I'm looking for. How do you do ?, a few days ago ask about how to load images contained within packages of the same project in JAVA that were not through URLs, because when generating the jar file, the program responds with errors.

Try to do the same with the GIF file, but not even the netbeans recognize it. . .

The assets package already contains the GIF.

I want to avoid using web links since at the moment there is a connection failure where it will be used, the program will crasheara (it closes).

How do I make it so that I can reproduce the gif using the file contained in the package of my project?

    
asked by TwoDent 31.01.2017 в 01:21
source

2 answers

4

What should work for you is to load the file in byte[] and then build the image using createImage(byte[] ba) :

// puedes usar org.apache.commons.io.IOUtils para obtener el Inputstream como byte[]
byte[] ba = IOUtils.toByteArray(getClass().getResourceAsStream( "/assets/source.gif" ));
Image image = Toolkit.getDefaultToolkit().createImage(ba);

As you can see, you load the content of your .jar resource in the same way as your other question . Only this time you load it into an array of bytes that you use to build your array image using% aw_% awt.

    
answered by 31.01.2017 / 01:55
source
2

I use this in a JLabel and then I add it to a JPanel.

jLabel1.setIcon(new ImageIcon(getClass().getResource("/res/drawable/loading.gif")));
    
answered by 31.07.2017 в 06:40