Writing highly reusable UI components in Java ME applications can be challenging, because they can present performance bottlenecks or be too application-specific. However, reusable and fast-performing components are possible if the components are made sufficiently simple. In the fully customized UI of the Paint MIDlet, some parts are so generic that they can be reused practically anywhere:
The Button
class is a good super class for
any UI element that can be touched. To see how the class is used in
this MIDlet, see the source code for any of the MIDlet classes ending
with "Tool".
Each subclass of Button
must override the onSelected
method, which is called
when the button is pressed (the overriding is forced by making the
method abstract). You can also attach listeners to the button and
make it a bit more flexible, because it allows n-number of classes
to receive a notification when the button is pressed. To make the Button
class receive touch events, you only have to add
a call to the pointerPressed
and pointerReleased
methods of the Canvas
, as shown in the following example:
Button button = new Button() { // ... }; public void paint(Graphics g) { button.render(g); } public void pointerPressed(int x, int y) { button.pressed(x,y); } public void pointerReleased(int x, int y) { button.unpressed(x,y); }
The Toolbar
class is an easily reusable wrapper
for many Buttons
, setting them in a line.
The FileDialog
class works with any new Series
40 device that support the TextEditor
class. You can override the buttonPressed
method to make it do something else when the OK or Cancel button is pressed.
By changing the graphics for the UI elements, you can easily customize the appearance of the UI and reuse the same elements elsewhere.