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 ...
Get J2ME in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.