Here is a sample layout for repainting constantly to show movement
import java.awt.*;
public class Sample implements Runnable {
Thread t;
public void init() {
t = new Thread(this);
t.start();
}
public void run() {
while (true) {
repaint();
try {
t.sleep(30);
} catch (InterruptedException e) {
}
}
}
public void paint(Graphics g) {
// whatever you need to paint
}
}
This will repeatedly repaint BUT there is an annoying flicker that comes with it. You could create a "double buffer" to fix that. (this example is for applets only)
import java.applet.Applet;
import java.awt.*;
public class Sample extends Applet implements Runnable {
Thread t;
Image img;
Graphics imageBuffer;
public void init() {
t = new Thread(this);
t.start();
// the getSize() call is the ONLY reason this is meant specifically for
// applets, because I don't know how to work around them.
img = createImage(getSize().width, getSize().height);
imageBuffer = img.getGraphics();
}
public void run() {
while (true) {
repaint();
try {
t.sleep(30);
} catch (InterruptedException e) {
}
}
}
public void paint(Graphics g) {
// the follow two lines are required
imageBuffer.setColor(Color.white); // sets background color
imageBuffer.fillRect(0, 0, getSize().width, getSize().height);
// example of how to use imageBuffer
imageBuffer.setColor(Color.black);
imageBuffer.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
imageBuffer.drawString("Hello World!", 5, 15);
g.drawImage(img); // NOTE: We draw the Image, not the Graphics imageBuffer
}
// IMPORTANT
public void update(Graphics g) {
paint(g);
}
}
If you know how big your Canvas is, then you can replace getSize().width or height with the width and height of your Canvas.
Credit:
GameDev.net - Java Game Programming Part II: Making a Simple Game