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

The Graphics Clip

Although the previous animation example works, it is rather inefficient. The main problem lies with the way the paint( ) method interacts with the moveAllBlocks( ) method. When the frame timer expires, moveAllBlocks( ) updates the coordinates of all the blocks and then arranges for paint( ) to be called, which then redraws the whole screen. Redrawing the entire screen is, of course, highly inefficient, because most of it has not changed. In fact, when a block moves, all that you really need to do is use the background color to paint the area that it used to occupy and then redraw the block in its new location. Because you can’t get hold of a Graphics object to do this directly within moveAllBlocks( ), you need some way to communicate to the paint( ) method that it doesn’t need to repaint everything. Fortunately, there is a simple way to do this that requires small modifications to both moveAllBlocks( ) and the paint( ) method.

In Example 5-3, moveAllBlocks( ) signals that a repaint is required by calling the Canvas repaint( ) method. The variant of repaint( ) that it uses signals to paint( ) that the whole screen needs to be redrawn, but there is a second version that can be used to pass more information:

public void repaint(int x, int y, int width, int height)

This method defines a rectangle that needs to be repainted, instead of the whole screen. Using this method, moveAllBlocks( ) can be rewritten as shown in Example 5-5 to indicate that only the old and new ...

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