-
Double buffering problem
I'm learning animations and have followed every possible tutorial I could find, but still my simple "animation" flickers.
First I tried to do a bouncing ball animation (three .gif frames), now I simply copied the code of this tutorial and tried to animate a moving car. It still flickers.
The Java Boutique: Java Tutorial: Java by Example: Fonts and Graphics - Page 20
I modified it a bit (instead of
Image car=getImage(getCodeBase(), "car.gif");
I use ImageIcon class to load my image and since I don't have a background image I clear the buffergraphics with clearRect(0,0,width, height))
The applet looks good on the website, but in eclipse it flickers a lot (as it does without the double buffering).
Here is my code, thanks for your help.
Code:
import java.awt.*;
import java.applet.*;
import javax.swing.ImageIcon;
public class flickerTest extends Applet implements Runnable
{
Thread runner;
private Image Buffer;
private Graphics gBuffer;
String filePath="...";
Image car = new ImageIcon(filePath+"/car.gif").getImage();
int x=0;
public void init()
{
//create graphics buffer
Buffer=createImage(getWidth(),getHeight());
gBuffer=Buffer.getGraphics();
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop() {
runner = null;
}
public void run()
{
while(true)
{
//Thread sleeps for 15 milliseconds here
try {Thread.sleep(15);}
catch (Exception e) {//
}
gBuffer.clearRect(0, 0, getHeight(), getWidth());
//move the car from left to right...
x++;
//if it moves past the right border,
//let it reappear on the left border
if(x>getWidth())
x=-125;
gBuffer.drawImage(car,x,150,null);
repaint();
}
}
//is needed to avoid erasing the background by Java
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
g.drawImage (Buffer,x,0, null);
}
}
-
Well this was aggravating. I used another program to create the .gif image and now it works perfectly. Go figure.
Previously I used a program called Pixen, now I opened the image and saved it in GIMP and it started working miraculously.:@::(party):