Painting and the Graphics Class

When the platform determines that the content of a Canvas needs to be drawn onto the screen, it calls the paint( ) method, which the MIDlet developer is required to implement:

protected void paint(Graphics g)

This method is called at the following times:

  • When the Canvas becomes visible as a result of the Display setCurrent( ) method being invoked

  • When some or all of the Canvas reappears after being partly or wholly obscured by an Alert or a system screen, such as a menu of Commands opened from a soft button

  • As a result of application code requesting that the screen be repainted following a change in the data that it is rendering

The Graphics object passed to the paint( ) method provides methods that allow graphics operations, such as line and text rendering and color filling, to be performed on its target. The target is either the screen itself or, in the case of a platform that supports double buffering, an off-screen image that will be copied to the screen when the paint( ) method returns. Implementing this method is the only way to get a Graphics object that can access the screen; unlike the J2SE Component class, Canvas does not have a getGraphics( ) method that can be used to get access on demand to the screen space that it occupies. Therefore, all screen updates must be performed in the paint( ) method. The MIDP specification prohibits holding a reference to the Graphics object passed to paint( ) for use elsewhere.[18]

When the visibility of ...

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.