The page class
package brf.j2me.midp.test;
import brf.j2me.midp.dynaworks.CanvasPage;
import brf.j2me.midp.dynaworks.events.*;
import javax.microedition.lcdui.*;
public class TestPage extends CanvasPage {
/**
* commands defined and handled by the application.
*/
private Command exitCommand =
new Command ("Exit", Command.SCREEN, 2);
private Command aboutCommand =
new Command ("About", Command.SCREEN, 1);
private int counter = 0;
|
The page class defines two commands: An "Exit" command that will terminate
the application and an "About" command that will show a (default) splash
screen.
There is one more attribute (counter) that will be used in the
page thread as an "tick" counter and is displayed on the screen.
/**
* constructor.
*/
public TestPage (String name) {
// pass page label
super (name);
// add commands.
addCommand (exitCommand);
addCommand (aboutCommand);
}
|
The page constructor initializes the base class and adds the defined
commands.
/**
* run the next slice of the application
*/
public void tick () {
// wait a bit ...
try {
Thread.sleep (100);
}
catch (InterruptedException e) {
}
// perform the step.
counter++;
repaint();
}
|
Every page runs its own "worker" thread, that loops until the application
is terminated. The tick() method of a page class is called for
each such loop.
If you want to display the result of your tick() method, you can call
repaint() to force a redraw of the screen.
Don't spent to much time in this routine, for the event handling is also running
inside this loop! No events can be processed while your tick() method
is running...
So, if your computation takes longer, make sure you check for events and terminate
the method, if there are any events pending. You can use something like:
public void tick () {
while (!eventsPending()) {
// perform the next step.
}
repaint();
}
|
Of course you have to make sure that your own loop doesn't consume too
much time...
/**
* render the data.
*/
public void paint (Graphics g) {
g.setColor (-1);
g.fillRect (0, 0, getWidth(), getHeight());
g.setColor (0);
g.drawString ("counter: " + counter,
getWidth()/2, getHeight()/2,
g.HCENTER | g.BASELINE);
}
|
This method is called whenever the screen needs to be redrawn. No magic here...
/**
* handle events.
*/
public boolean handleEvent (Event e) {
// is this a command event?
if (e.getCode() == PageEvent.PAGE_CMD) {
// get the command code.
String cmd = ((PageEvent)e).getAction();
// exit application
if (cmd.compareTo ("Exit") == 0) {
exit (null);
return true;
}
}
// pass event to base class.
return super.handleEvent (e);
}
}
|
The most important method is the handleEvent() method. It will receive
any events sent by the device or the framework - especially the command events
we have defined for the page.
The sample application only handles the "Exit" command; the "About" command
is handled by the page base class.
|