Drawing Lines and Arcs

The Graphics class methods that let you draw straight lines, rectangles, and arcs are very similar to those available in J2SE. There are, of course, none of the advanced features provided by Java 2D. Even some of the more basic features, such as convenience methods that let you draw polygons and polylines, are missing, although some of them can easily be simulated.

The drawing primitives work by determining the set of pixels that will be affected and setting each of them to the value of the current color attribute as set by setColor( ) or setGrayScale( ). Because there is no support for transparency and color blending, no account is taken of the initial state of an affected pixel.

Perhaps surprisingly, no provision is made for an “exclusive-or” drawing mode, in which the new pixel value is combined with the existing one using a bitwise exclusive-or operation. This is not an issue, in practice, because MIDlets have access to a Graphics object only in the paint( ) method, when everything must be redrawn, whether it has moved or not. By contrast, it is possible in J2SE to get a Graphics object at any time, and, therefore, parts of the screen can be updated directly, without having to wait for the paint( ) method to be called.

Lines and Rectangles

The simplest shape you can draw on a Canvas is a straight line:

public void drawLine(int x1, int y1, int x2, int y2)

This method draws a line between the two pixels at (x1, y1) and (x2, y2). Usually, both these points ...

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.