0

I'm doing a game and when a ship is dead, I make a Thread that shows a GIF explosion. The problem is that sometimes that explosion doesn't disappear, and stays on the screen until the game is over.

Debugging, I saw "Daemon Thread Image Animator -0" running and I guess that the GIF. This is the code of the explosion:

public void run(){
    setIcon(new ImageIcon(getClass().getClassLoader().getResource("Imag/explosion.gif")));
    Point pos = this.getLocation();
    setBounds(pos.x,pos.y);
    try{
        Thread.sleep(500);
    }
    catch(Exception e){
        e.printStackTrace();
    }
    juego.removeEntidad(this);

}

Sometimes this problem doesn't happen and I don't know how to fix it.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Joseph
  • 45
  • 6
  • too hard to say something, nor if is there user Thread.sleep(int) together with Swing (more info in Oracle tutorial EventDispatchThread), for better help sooner SSCCE/MCVE, short, runnable, compilable – mKorbel Nov 22 '14 at 15:37

1 Answers1

1

I'm doing a game and when a ship is dead, I make a Thread that shows a GIF explosion.

Yes, you need to use a Thread, but you should NOT be updating GUI components in the Thread.

Instead you should probably be using a SwingWorker. Read the section from the Swing tutorial on Concurrency in Swing for more information and examples of using a SwingWorker.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Hi, the problem is that in order to use SwingWorker I need that the class extends it. But I am extending JLabel and I cant make a Multiple inheritance – Joseph Nov 22 '14 at 16:03
  • @Mario: Then use composition, for [example](http://stackoverflow.com/a/11372932/230513), with the label & worker contained in the same class. – trashgod Nov 22 '14 at 16:43