The ColorPicker
class is much easier to implement
than it looks. The basic idea is to show a large color palette where
the user can pick the desired color by touching the color palette
area: you draw an image of the color palette on the screen, and when
the user touches it, you use the Graphics
class to identify the color under
the user's finger.
Figure: Changing the color
To implement the color selection:
Use the pointerDragged
and pointerReleased
methods
to grab the touch event while the color palette is shown.
public void pointerDragged(int x, int y, int id) { if (!drawingAllowed && colorpicker.isVisible()) { colorpicker.dragged(x, y); } // ... } public void pointerReleased(int x, int y, int id) { if (!drawingAllowed) { if (colorpicker.isVisible()) { colorpicker.pressed(x, y); } else if (savedialog.isVisible()) { savedialog.pointerUnpressed(x, y); } } // ... }
The MIDlet grabs
the touch event when the finger is lifted from the screen, because
the same action is used to close the ColorPicker
when
a color has been selected. The pressed
method checks
which color is at the touch event’s coordinates.
The background variable (the color palette image) is used to determine
which RGB value is at the point where the user pressed, and then that
new color is emitted to all the classes that implement the ColorChangeListener
interface and have been registered to
listen to it. If the touch event is outside the ColorPicker
, the color palette view is simply closed.
public void dragged(int x, int y) { selectColor(x, y); } public void pressed(int x, int y) { selectColor(x, y); // hide me Main.getInstance().getDrawArea().hideColorPicker(); } // ... private void selectColor(int x, int y) { if (area.isPointInside(x, y)) { int[] argb = new int[1]; palette.getRGB(argb, 0, 1, x - this.x, y - this.y, 1, 1); int rgb = argb[0] & 0x00FFFFFF; int l = listeners.size(); for (int i = 0; i < l; i++) { ColorChangeListener listener = (ColorChangeListener) listeners.elementAt(i); listener.colorChanged(rgb); } } }