Tuesday, March 17, 2009

How to : Make list items appear on a screen

How To To create a list of selectable items, the ListField class is needed and the ListFieldCallback interface must be implemented. ListField is the displayable field object and the ListFieldCallback interface is responsible for drawing the list elements to the screen. The ListFieldCallback drawListRow() method is called automatically by the system for each element in the list.

The following is a sample implementation of ListFieldCallback:

private class ListCallback implements ListFieldCallback {
private Vector listElements = new Vector();
public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
String text = (String)listElements.elementAt(index);
g.drawText(text, 0, y, 0, w);
}
public Object get(ListField list, int index) {
return listElements.elementAt(index);
}
public int indexOfList(ListField list, String p, int s) {
//return listElements.getSelectedIndex();
return listElements.indexOf(p, s);
}
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
}
public void insert(String toInsert, int index) {
listElements.insertElementAt(toInsert, index);
}
public void erase() {
listElements.removeAllElements();
}
}

To create an instance of ListField

ListField _list = new ListField();

To create an instance of ListCallback, which is an implementation of the ListFieldCallback interface, use the following:

ListCallback _callback = new ListCallback();

After creating instances of ListField and ListCallback, an association between the two can be created by calling the ListField setCallback() method as follows:

_list.setCallback(_callback);

Now that the list has been initialized, items can be added to it as follows:

_list.insert(index);
_callback.insert(name, index);

Where name is the String that represents the name of the selectable item in the list and index is a number (int) that represents the position of the item in the list.

No comments:

Post a Comment

Place your comments here...