A Simple Animation MIDlet
So
far, all the Canvas examples have involved drawing
shapes onto the screen when the platform calls the paint( ) method. If the content of the Canvas
is static, it is sufficient to draw it only when the platform detects
that the screen content has been partly or completely overwritten by
an Alert, or when a different MIDlet screen is
shown and then removed. If you want to display dynamic content,
however, you can’t wait for the platform to call
paint( ), because you need to repaint the
Canvas whenever the dynamic content changes.
For example, suppose you wanted to create a simple animation that involves moving small blocks around the screen. In order to do this, you might create a class to represent each block by recording its x and y coordinates and its speeds along the x and y axes:
class Block {
int x; // X position
int y; // Y position
int xSpeed; // Speed in the X direction
int ySpeed; // Speed in the Y direction
}The Canvas
paint( ) method then
fills its background with an appropriate color and loops over the set
of blocks, drawing a filled rectangle for each, using its current
coordinates to determine the location of its corresponding rectangle.
Example 5-2 shows how you might implement this for a
set of square blocks represented by an array of
Block objects in an array called
blocks.
Example 5-2. Painting Blocks onto a Canvas
protected void paint(Graphics g) { // Paint with the background color g.setColor(background); g.fillRect(0, 0, width, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access