Java Reference
In-Depth Information
public void run() {
int permille = (int) ((System.currentTimeMillis()
- startTime) / seconds);
degree = 360 - (permille * 360) / 1000;
repaint();
}
}
As always, you need a MIDlet to actually display your StopWatchCanvas implementation. The
following code creates a stopwatch set to 10 seconds when the application is started:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class StopWatch extends MIDlet {
public void startApp() {
Display display = Display.getDisplay (this);
display.setCurrent (new StopWatchCanvas (display, 10));
}
public void pauseApp() {
}
public void destroyApp (boolean forced) {
}
}
Avoiding Flickering
On some devices, the stopwatch implementation will flicker. This is due to the fact that the display is
cleared completely before a new stopwatch is drawn. However, on some other devices, the stopwatch
will not flicker because those devices provide automated double buffering. Before the screen is updated,
all drawing methods are performed in a hidden buffer area. Then, when the paint() method is
finished, the complete display is updated from the offscreen buffer at once. The method
isDoubleBuffered() in the Canvas class is able to determine whether the device screen is
double buffered.
In order to avoid flickering of your animation in all cases, you can add your own offscreen image,
which is allocated only if the system does not provide double buffering:
Image offscreen = isDoubleBuffered() ? null :
Image.createImage (getWidth(), getHeight());
In the paint() method, you just check if the offscreen image is not null , and if so, you delegate all
drawing to your offscreen buffer. The offscreen buffer is then drawn immediately at the end of the
paint() method, without first clearing the screen. Clearing the screen is not necessary in that case
since the offscreen buffer was cleared before drawing and it fills every pixel of the display:
public void paint (Graphics g) {
Graphics g2 = offscreen == null ? g : offscreen.getGraphics();
g2.setGrayScale (255);
g2.fillRect (0, 0, getWidth(), getHeight());
if (degree > 0) {
g2.setColor (255, 0, 0);
g2.fillArc (0,0, getWidth(), getHeight(), 90, degree);
display.callSerially (this);
Search WWH ::




Custom Search