Try it this way:
g.clearRect(x, y, width, height);
Clears the specified rectangle by filling it with the background color of the
current drawing surface. This operation does not use painting mode
current.
Starting with Java 1.1, the background color of Offscreen images
can depend on the system. Applications must use setColor
followed
of fillRect
to ensure that an off-screen image is cleaned for
a specific color.
Click here for documentation!
[UPDATING]
In this code above, this will work because it is painting the same canvas
within a for
.
There are several ways to accomplish this animation!
Follow an example using the repaint()
of a JComponent
through a Thread
:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Animation extends JComponent implements Runnable, ImageObserver {
private static final long serialVersionUID = 333L;
/**
* Controla/Conta qual frame está sendo exibido
*/
public int frame = 0;
/**
* Entre as animações
*/
public int delay = 99;
/**
* Sequencia de imagem que vamos exibir
*/
Image[] split = new Image[5];
/**
* Responsável por redesenhar a tela!
*/
Thread animatorThread;
/**
* Inicializando as sequencia de imagens e Thread que realiza o controle
*/
public void init() {
split[0] = Toolkit.getDefaultToolkit().getImage("0.png");
split[1] = Toolkit.getDefaultToolkit().getImage("1.png");
split[2] = Toolkit.getDefaultToolkit().getImage("2.png");
split[3] = Toolkit.getDefaultToolkit().getImage("3.png");
split[4] = Toolkit.getDefaultToolkit().getImage("4.png");
animatorThread = new Thread(this);
animatorThread.start();
}
public void run() {
while (frame != 999) {
/**
* Re pinta a tela
*/
repaint();
frame++;
try {
Thread.sleep(delay);
} catch (final InterruptedException e) {
e.printStackTrace();
break;
}
}
}
public void paint(final Graphics g) {
/**
* Utilizamos o resto da divisão por cinco para pegar a posição
*/
int i = frame % 5;
// e printa a imagem
g.drawImage(split[i], 10, 10, this);
}
public static class Graphics2DDrawImage {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
final Animation animation = new Animation();
window.getContentPane().add(animation);
window.setVisible(true);
animation.init();
}
}
}
clearRect clears imageicon too? I think only drawings, but images I don’t think clean. a simple repaint would be enough.
– user28595