Sunday, April 19, 2009

Adding colors

Since MIDP 2.0 it is possible to discover some colors defined by the handset user.
There is a new method Display.getColor(int), the parameter may be one of six public constants from class Display: COLOR_BACKGROUND, COLOR_BORDER, COLOR_FOREGROUND, COLOR_HIGHLIGHTED_BACKGROUND, COLOR_HIGHLIGHTED_FOREGROUND, COLOR_HIGHLIGHTED_BORDER. The return is a valid color to be used with Graphics.setColor(int).
These colors are the same from the handset main screens - the current theme.
To use these colors lets define five more attributes at our CustomImplicitList:
private int backgroundColor = 0xffffff;
private int foregroundColor;
private int backgroundhHighlightColor = 0xffffff;
private int foregroundHighlightColor;
private int borderHighlightColor;
And add setter method for each one of them.
The value used to initiate backgroundColor and backgroundhHighlightColor represents the white color.
Lets say there are two variables: CustomImplicitList list and a Display display.
list.setBackgroundColor(display.getColor(Display.COLOR_BACKGROUND));
list.setForegroundColor(display.getColor(Display.COLOR_FOREGROUND));
list.setBackgroundhHighlightColor(display.getColor(Display.COLOR_HIGHLIGHTED_BACKGROUND));
list.setForegroundHighlightColor(display.getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND));
list.setBorderHighlightColor(display.getColor(Display.COLOR_HIGHLIGHTED_BORDER));
We are not using COLOR_BORDER because the border of our CustomImplicitList is used only at the selected element.
The last part is to change the paint method of CustomImplicitList:
g.setColor(this.backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
// ...
for (int i = 0; i < this.items.length; i++) {
if (i == this.selectedIndex) {
g.setColor(this.backgroundhHighlightColor);
g.fillRect(1, y, getWidth() - 3, font.getHeight());
g.setColor(this.borderHighlightColor);
g.drawRect(1, y, getWidth() - 3, font.getHeight());
g.setColor(this.foregroundHighlightColor);
} else {
g.setColor(this.foregroundColor);
}
g.drawString(this.items[i], getWidth() / 2, y, Graphics.HCENTER Graphics.TOP);
y += font.getHeight();
// it was the last line that could be drawn
if (y + font.getHeight() > height) {
i = this.items.length;
}
}

No comments: