Java Reference
In-Depth Information
CHAPTER 7
■ ■ ■
Custom Items
I n the last chapter, you learned about Form s, the most flexible and powerful descendents of
javax.microedition.lcdui.Screen . Form s are essentially collections of Item s. The MIDP APIs
include a useful toolbox of Item subclasses, everything from text and image display to interac-
tive date fields and gauges.
You can have even more power through the opportunity to define your own items. In this
chapter, you'll learn how to create items that do their own drawing and respond to user input.
Introducing CustomItem
The class that makes custom items possible is appropriately named CustomItem . Like all items
that live in a Form , it is a subclass of Item . To create your very own item, all you have to do is
define a subclass of CustomItem by implementing five abstract methods. The first four, listed
next, have to do with the size of the item's content area , which is the area for which your code
has responsibility. The total area of the custom item includes a label and perhaps borders, but
these are the responsibility of the implementation. Your CustomItem subclass is only respon-
sible for the content area.
protected int getPrefContentWidth(int height)
protected int getPrefContentHeight(int width)
protected int getMinContentWidth()
protected int getMinContentHeight()
The first two methods should return values that define how big your item wants to be.
When the MIDP implementation lays out a Form containing your item, it may not be able to
honor your preferred size, but it will try. The implementation passes a proposed height and
width into these methods to give your item class an idea of what its dimensions might eventually
be. For example, the implementation might call your item's getPrefContentWidth() method
and pass a value of 18 for the height parameter. This is the implementation asking your item,
“What width would you like to be if I make your height 18?”
The second pair of methods should return information about the minimum size of the
item. This is the smallest size that your item believes it can tolerate.
The fifth method that must be defined by a concrete CustomItem subclass is the paint()
method, which the implementation calls to render the item.
protected void paint(Graphics g, int w, int h)
89
Search WWH ::




Custom Search