Java Reference
In-Depth Information
run() method of the Runnable object is then executed serially like any other event handling
method. In the run() method, the next frame can be set up, and a new repaint can be requested there.
To demonstrate this execution model, you will build a simple stopwatch that counts down a given
number of seconds by showing a corresponding pie slice using the fillArc() method, as shown in
Figure 3.21 .
Figure 3.21. A very simple stopwatch.
The Canvas implementation stores the current slice in degree, the start time, the total amount of
seconds and the MIDlet display in local variables. In order to make use of callSerially() , your
Canvas implements the Runnable interface:
class StopWatchCanvas extends Canvas implements Runnable {
int degree = 360;
long startTime;
int seconds;
Display display;
When the StopWatchCanvas is created, you store the given display and seconds. Then, the current
time is determined and stored, too:
StopWatchCanvas (Display display, int seconds) {
this.display = display;
this.seconds = seconds;
startTime = System.currentTimeMillis();
}
In the paint() method, you clear the display. If you need to draw more than 0 degrees, you fill a
corresponding arc with red color and request recalculation of the pie slice using callSerially() .
Finally, you draw the outline of the stopwatch by setting the color to black and calling drawArc() :
public void paint (Graphics g) {
g.setGrayScale (255);
g.fillRect (0, 0, getWidth(), getHeight());
if (degree > 0) {
g.setColor (255, 0, 0);
g.fillArc (0,0, getWidth(), getHeight(), 90, degree);
display.callSerially (this);
}
g.setGrayScale (0);
g.drawArc (0, 0, getWidth()-1, getHeight()-1, 0, 360);
}
This method is invoked by the event handling thread as a result of the previous
display.callSerially(this) statement. In this case, it just calculates a new pie slice and
requests a repaint() :
 
Search WWH ::




Custom Search