Double buffering still gives flickering graphics.
843807Jan 21 2010 — edited Jan 23 2010I copied code from a tutorail which is supposed to illustrate double buffering.
After I run it, it still flickers though.
I use applet viewer, which is part of netbeans to run my applet.
Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
My questions are:
Is the strategy used for double buffering correct?
Why does it flicker?
Why does the program change the priority a couple of times?
Can you make fast games in JApplets or is there a better way to make games? (I think C++ is too hard)
Here is the code:
package ballspel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
//import java.applet.*;
/**
*
* @author Somelauw
*/
public class BallApplet extends /*Applet*/ JApplet implements Runnable {
private Image dbImage;
private Graphics dbg;
private int radius = 20;
private int xPos = 10;
private int yPos = 100;
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
@Override
public void init() {
//System.out.println(this.isDoubleBuffered()); //returns false
// Isn't there a builtin way to force double buffering?
// TODO start asynchronous download of heavy resources
}
@Override
public void start() {
Thread th = new Thread(this);
th.start();
}
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true) {
xPos++;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
//g.clear();//, yPos, WIDTH, WIDTH)
g.setColor(Color.red);
g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
}
@Override
public void update(Graphics g) {
super.update(g);
// initialize buffer
if (dbImage == null) {
dbImage = createImage(this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
}
// clear screen in background
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor(getForeground());
paint(dbg);
// draw image on the screen
g.drawImage(dbImage, 0, 0, this);
}
// TODO overwrite start(), stop() and destroy() methods
}