Java Reference
In-Depth Information
The example clears the screen by setting the color to white and filling a rectangle the size of the screen,
determined by calling
getWidth()
and
getHeight()
. Then it draws a line from coordinates (0,0)
to (100,200). Finally, it draws a rectangle starting at (20,30), 30 pixels wide and 20 pixels high:
import javax.microedition.lcdui.*;
class DrawingDemoCanvas extends Canvas {
public void paint (Graphics g) {
g.setGrayScale (255);
g.fillRect (0, 0, getWidth(), getHeight());
g.setGrayScale (0);
g.drawLine (0, 0, 100, 200);
g.fillRect (20, 30, 30, 20);
}
}
As you can see in the example code, you create a custom class
DrawingDemoCanvas
in order to fill
the
paint()
method. Actually, it is not possible to draw custom graphics without creating a new class
and implementing the
paint()
method.
Here's the missing code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class DrawingDemo extends MIDlet {
public void startApp() {
Display.getDisplay (this).setCurrent (new
DrawingDemoCanvas());
}
public void pauseApp() {}
public void destroyApp (boolean forced) {}
}
Now you can start your
DrawingDemo
MIDlet. Depending on the screen size of the device, it will
create output similar to
Figure 3.9
.
In most subsequent examples, you will omit the MIDlet since it is
basically the same as this one, except that the name of your
Canvas
class will be different.
Figure 3.9. Output of the
DrawingDemo
MIDlet.
In the example, the screen is cleared before drawing because the system relies on the
paint()
method to fill every pixel of the draw region with a valid value. You don't erase the previous content of
the screen automatically because doing so may cause flickering of animations. The application cannot
make any assumptions about the content of the
Screen
before
paint()
is called. The screen may be
filled with the content drawn at the last call of
paint()
, but it may also be filled with an alert box
remaining from an incoming phone call, for example.
Search WWH ::
Custom Search