Hi,
I am working my way through de basics of Java with the intention to go on creating games with it.
As far as I know there are 3 ways to update your applet:
- no repaint, just paint the changes
- repaint();
- double buffering;
The last is set to be the best.
Well, I’ve written a little experiment. I create a little rectangle and tell it to bounce around in my applet window. To update the applet I use double buffering. (At least I am convinced I do )
The source is included at the end of this post.
When I run the code I don’t see a smooth movement of the rectangle. Instead it’s a kind of blury with a motion trail.
Am I doing something wrong? Or are there better approaches to update the ‘screen’?
Thanks for any advice,
JustMe
/*
* Main.java
*
* Created on 5 december 2005, 20:15
*
* First try: Just moving a rectangle across the screen
*
*/
import java.applet.*;
import java.awt.*;
public class Main extends Applet implements Runnable {
// vars for double buffering
private Image dbImage;
private Graphics dbg;
//rectangle vars
int x_pos = 10;
int y_pos = 100;
int x_width = 8;
int y_height = 20;
int x_speed = 4; //pixels per move
int y_speed = 4; //pixels per move
public void init() {
//resize the applet
this.setSize( 640, 480 );
}
public void start() {
// define a new thread
Thread th = new Thread(this);
// start this thread
th.start();
}
public void stop() { }
public void destroy() { }
public void run() {
this.setBackground(Color.blue);
// lower ThreadPriority
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
// run a long while (true) this means in our case "always"
while (true) {
x_pos = x_pos + x_speed;
if( (x_pos + x_width) >= this.getSize().width || x_pos <= 0 )
{
x_speed = - x_speed;
}
y_pos = y_pos + y_speed;
if( ( y_pos + y_height ) >= this.getSize().height || y_pos <= 0 )
{
y_speed = - y_speed;
}
// repaint the applet
repaint();
try {
// Stop thread for 20 milliseconds
Thread.sleep( 20 );
} catch (InterruptedException ex) {
// do nothing
}
// set ThreadPriority to maximum value
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
/* Update - Double buffering */
public void update(Graphics 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);
}
public void paint(Graphics g) {
//Put things on the screen...
g.setColor( Color.red );
g.fillRect( x_pos,y_pos, x_width, y_height );
}
}