Search code examples
javagraphicsgifgraphics2d

Why is my gif animation in paintComponent not working?


I am creating a Java game, and in this, I have a plane that can be moved around by the user, however if the plane hits any of the sides, it should explode - meaning there should be an explosion at that location. I used links such as: Why gif animation doesn't animate when using it in paintComponent()? and other ones to find out how to animate a gif, however, my code doesn't work.

Here is the relevant code:

            ImageIcon ii = new ImageIcon(this.getClass().getResource("explosion.gif"));
            Graphics2D g2d = (Graphics2D)g;
            
            g2d.drawImage(ii.getImage(), planeX, planeY, this);
            System.out.println("drawn");

Although "drawn" is being printed out on the console, the explosion gif doesn't load. I checked the file name and it was correct. However, I did use the same gif somewhere else in my code and it worked there, so is there something that prevents having a gif being used twice in Java?

Here is my entire paintComponent() method:

        super.paintComponent(g);
        
        setFocusable(true);
        requestFocus();
        
        background = new ImageIcon("bg.png").getImage();
        g.drawImage(background, -6, 0, 700, 700, null); //background of JPanel
        
        if (!hit) g.drawImage(plane, planeX, planeY, planeLen, planeHei, null);  //only draw plane if not exploded
        else if (count == 0) 
        {
            ImageIcon ii = new ImageIcon(this.getClass().getResource("explosion.gif"));
            Graphics2D g2d = (Graphics2D)g;
            
            g2d.drawImage(ii.getImage(), planeX, planeY, this); //doesn't work
            System.out.println("drawn"); //printed
        }

        title = new ImageIcon("title.png").getImage(); //transparent, is drawn
        g.drawImage(title, -9, 20, 700, 218, null);
        
        title2 = new ImageIcon("title2.png").getImage(); //transparent, is drawn
        g.drawImage(title2, 10, 245, 670, 20, null);

I have checked title and title2 and they are transparent, meaning that the explosion should be seen. I even tried it below those two images, and the explosion still is not visible. I am using JButtons and KeyListeners on this panel as well.

Please let me know if I should add anything else, and thank you in advance!


Solution

  • Never mind, I had to make a duplicate of "explosion.gif". It works fine now! However, please let me know if there is another way of doing this, much faster AND efficiently. Thanks!