O'Reilly logo

J2ME in a Nutshell by Kim Topley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required