Java Reference
In-Depth Information
CustomItem Painting
As you've seen, a CustomItem is drawn on the screen in its paint() method. This method is
passed a Graphics object that serves two purposes. First, it represents the drawing surface of
the CustomItem 's content area. Second, it provides numerous methods for drawing shapes, images,
and text. We won't cover all of these methods until Chapter 13, but you'll see a couple of them
in the examples in this chapter: for instance, drawString() renders text, while drawLine()
renders a straight line.
The paint() method is an example of a callback , a method in your code that is called by the
MIDP implementation. The implementation calls paint() whenever it needs to show your
custom item on the screen. It calls other methods to find out the minimum and preferred sizes
of your component when its containing form is being laid out. It's the implementation's job to
show the whole screen; it just calls your paint() method to show the part of the screen occu-
pied by your custom item. You don't tell the implementation when to draw your item; you just
tell it that your item is part of a form, and then it figures out how to show everything.
If something needs to change in your custom item's appearance, you can request a refresh
by calling the repaint() method. This method signals to the implementation that your item
needs to be drawn. In response, the implementation will soon call the paint() method again.
For optimized drawing, you may only wish to redraw part of the item. In this case, use
repaint(int x, int y, int width, int height) to describe a rectangular region of the item
that needs to be drawn.
Two methods return information that can help you make your item's appearance consis-
tent with the device's look and feel. The first is getColor() in the Display class. This method
returns an int representing a color when you supply one of the following constants:
COLOR_BACKGROUND
COLOR_BORDER
COLOR_FOREGROUND
COLOR_HIGHLIGHTED_BACKGROUND
COLOR_HIGHLIGHTED_BORDER
COLOR_HIGHLIGHTED_FOREGROUND
For example, you could set the current drawing color to the system's highlighted foreground
color with the following code:
public void paint(Graphics g) {
// Display mDisplay = ...
int fhc = mDisplay.getColor(
Display.COLOR_HIGHLIGHTED_FOREGROUND);
g.setColor(fhc);
// Draw stuff ...
}
Similarly, if you want any text drawn by your custom item to harmonize with other items
in a Form , you can retrieve an appropriate Font using the following method in the Font class:
public static Font getFont(int fontSpecifier)
Search WWH ::




Custom Search