Painting and Repainting

Team-Fly

The MIDP implementation calls a Canvas's paint() method when the contents of the Canvas need to be shown. This paint() method should look familiar to anyone who has ever implemented a custom Swing or AWT component.

The MIDP implementation passes a Graphics object to your paint() method. Graphics has methods for drawing shapes, text, and images on a Canvas. A typical Canvas implementation, then, looks something like this:

 import javax.microedition.lcdui.*; public class JonathanCanvas     extends Canvas {   public void paint(Graphics g) {     // Draw stuff using g.   } } 

What if you want to tell the Canvas to draw itself? You can't call paint() directly, because you don't have a suitable Graphics to pass to paint(). Instead, you need to tell the MIDP implementation that it's time to paint the Canvas. The way you do this is by calling repaint(). The first version of this method simply tells Canvas to paint everything.

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

The second version is a way of saying, "I only want you to paint this rectangular portion of the screen." If the drawing you're doing is very complicated, you can save some time by only painting the portion of the Canvas that has changed. This is implemented using a technique called clipping. A later section discusses clipping in more detail.

How exactly does repaint() work? When you call repaint(), paint() won't be called right away. The call to repaint() just signals to the MIDP implementation that you want the screen to be painted. Some time later, the implementation services the repaint request, which results in an actual call to the paint() method of the Canvas. The MIDP implementation may even combine several repaint requests, particularly if their repaint regions overlap.

Tip 

Canvas does not automatically clear itself when you call repaint(). If you want to change what's on the screen, rather than adding to it, you should clear the screen yourself in the paint() method. You'll see how to do this in the FontCanvas example later in this chapter.

An application can force the implementation to service all the repaint requests by calling serviceRepaints() on the Canvas object. This method does not return until all pending repaint requests have been serviced. If you are going to call serviceRepaints(), you should make sure that you aren't trying to acquire object locks in the paint() method that won't be released until serviceRepaints() returns. In general, you won't need to call serviceRepaints(); you can usually use Display's callSerially() method instead. (See the "Multithreading and Animation" section of this chapter for a discussion of callSerially().)


Team-Fly


Wireless Java. Developing with J2ME
ColdFusion MX Professional Projects
ISBN: 1590590775
EAN: 2147483647
Year: 2000
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net