I’m using a thread to display an animation with a sprite.
Explosion e2 = new Explosion(this, x2, y2, explosion);
new Thread(e2).start();
And in the explosion class I have :
public void run()
{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cursor++;
}
};
Timer timer = new Timer(50, taskPerformer);
while(cursor < (sprite.getNbSprite()-1))
{
timer.start();
drawExplosion();
}
timer.stop();
compteur--;
}
public void drawExplosion()
{
Graphics g = board.getGraphics();
board.repaint();
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprite.getSprite(cursor), x, y, this);
g.dispose();
}
But during the display I have a problem , between each image of the sprite there is a blank.
Like if the display is twinkling.
How can I have a fluid displaying ?
Thanks
EDIT ———————–
I’ve one more question.
In my Board class i’ve I put my explosion in an ArrayList.
But I’ve to delete the object in the ArrayList when the explosion thread end.
Do I have an ArrayList to stock all my explosion thread and when a thread end I delete the object in the explosion ArrayList.
public class Board extends JPanel{
Mouse mouse;
ArrayList<Explosion> explosions;
Sprite explosion;
public Board()
{
mouse = new Mouse(this);
explosion = new Sprite(320,320,5,5,"files/explosion2.png");
explosions = new ArrayList();
setDoubleBuffered(true);
this.addMouseListener(mouse);
}
public void addExplosion(int x, int y)
{
for(int i=0; i<100; i++)
{
int x2 = (int)(Math.random() * 450);
int y2 = (int)(Math.random() * 450);
Explosion e2 = new Explosion(this, x2, y2, explosion);
explosions.add(e2);
new Thread(e2).start();
}
}
public void removeExplosion(Explosion e)
{
explosions.remove(e);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
for(int i=0; i<explosions.size(); i++)
{
g2d.drawImage(explosion.getSprite(explosions.get(i).getCursorI()), explosions.get(i).getX(), explosions.get(i).getY(), this);
}
g.dispose();
}
}
In Swing, you must do everything related to Swing in the EDT.
You see some blinking because there is some painting done on
boardin two different threads and painting two different things.What you have to do is create a
class BoardWithSprite extend JPanelwhich overrides its
paintComponent(g)method such that it paints the sprite.Then you can just call
boardWithSprite.repaint()and it will do the painting correctly on the Swing EDT.