Java Reference
In-Depth Information
Graphics g = getGraphics();
while(true) {
// Check for user input.
// Update game state.
// Draw stuff using g.
flushGraphics();
}
To subclass GameCanvas , you need to call its protected constructor from your subclass's
constructor. This constructor accepts a single boolean argument, which indicates whether the
normal key event mechanism should be suppressed for the GameCanvas instance. The normal
key event mechanism refers to the callback mechanism of keyPressed() , keyReleased() ,
and keyRepeated() . Suppressing the normal mechanism may result in better performance.
GameCanvas provides an alternative method for responding to key events, which is detailed
in the next section.
To show how GameCanvas works for drawing, we'll rewrite the SweepCanvas example from
Chapter 13 using GameCanvas (see Listing 14-1). Note that the subclass no longer overrides
paint() . All the action happens in run() , which is executed in a separate thread that drives the
animation. The run() method calls render() , which does the actual drawing (and is identical to
the old paint() ).
Listing 14-1. Using GameCanvas for Animation
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class SweepGameCanvas
extends GameCanvas
implements Runnable {
private boolean mTrucking;
private int mTheta;
private int mBorder;
private int mDelay;
public SweepGameCanvas() {
super(true);
mTheta = 0;
mBorder = 10;
mDelay = 50;
}
public void start() {
mTrucking = true;
Thread t = new Thread(this);
t.start();
}
Search WWH ::




Custom Search