Java Reference
In-Depth Information
thread is responsible for operating the user interface, holding it up with lengthy computations
will make your application look lobotomized. Suppose, for example, that you had to retrieve
some data from the network. In response to a command, you might do something like this:
public void commandAction(Command c, Displayable s) {
if (c == mNetworkCommand) {
// Create a progress screen, progressScreen.
mDisplay.setCurrent(progressForm);
// Now do the network stuff.
// Oops! Users never see progressScreen.
}
// ...
}
The problem is that the progress screen won't be shown. The commandAction() method is
called from the user-interface thread, the same thread that's responsible for painting the
screen. If you tie up this thread with some lengthy processing of your own, the user-interface
thread never has a chance to update the screen. If you need to do something that takes a long
time, create a separate thread for it. In the Jargoneer example in Chapter 2, for example, network
access was performed in a separate thread.
In certain situations, you will need to ask the user-interface thread to execute code on your
behalf. If you are showing an animation, for example, you'll want to make sure that the frames
of the animation are properly synchronized with the repainting cycle. Otherwise, you're likely
to end up showing frames that are partially drawn.
Display has a mechanism for executing your code in the user-interface thread. It has a
method, callSerially() , that accepts a Runnable . When the user-interface thread is ready,
meaning when it has finished servicing all repaint requests, it will execute the run() method of
the Runnable from the user-interface thread. A typical animation, then, looks like this:
public class AnimationCanvas
extends Canvas
implements Runnable {
public start() {
run();
}
public void paint(Graphics g) {
// Paint a frame of the animation.
}
public void run() {
// Update our state.
// Now request a paint of the new frame.
repaint();
Display.callSerially(this);
}
}
Search WWH ::




Custom Search