Hi
I´m trying to move a filled rectangle by increasing the x-position by one in a applet, but it flickers. I´m not sure if the code below is the right way to go but this is how I have programmed?
Code:
public class Game extends Applet implements Runnable
{
private BufferedImage bi = null;
private TexturePaint paint = null;
private Graphics2D g2d = null;
private Rectangle rect = new Rectangle(0,0,50,50);
private Boolean isRunningFirstTime = true;
private Thread thread = null;
private int x = 0;
public void init()
{
}
public void paint(Graphics g)
{
update(g);
}
public void update(Graphics g)
{
if (isRunningFirstTime)
{
bi = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.setColor(Color.red);
g2.fillRect(0, 0, 50, 50);
paint = new TexturePaint(bi, new Rectangle(50, 50));
isRunningFirstTime = false;
}
g2d = (Graphics2D) g;
g2d.setColor(Color.white);
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.setPaint(paint);
g2d.fill(rect);
}
public void run()
{
while (thread != null)
{
rect.setLocation(x+=1, 0);
repaint();
try
{
Thread.sleep(10);
}
catch (InterruptedException error)
{
}
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
thread = null;
}
}
As I said, it flickers! How do I solve this?