Java Reference
In-Depth Information
Display display;
Face face = new Face (this);
int weight = IDEAL_WEIGHT;
Timer consumption;
int score;
public int getHappiness() {
int happiness = 20 - (weight > IDEAL_WEIGHT
? 10 * weight / IDEAL_WEIGHT
: 10 * IDEAL_WEIGHT / weight);
if (happiness < 0) happiness = 0;
else if (happiness > 10) happiness = 10;
return happiness;
}
public boolean isDead() {
return getHappiness() == 0;
}
public void transform (int amount) {
if (!isDead()) {
weight += amount;
face.repaint();
}
}
public void startApp() {
display = Display.getDisplay (this);
display.setCurrent (face);
consumption = new Timer();
consumption.scheduleAtFixedRate (new Consumption (this), 500,
500);
}
public void pauseApp() {
consumption.cancel();
}
public void destroyApp (boolean forced) {
}
}
Animation
With animation, there are normally two main problems: Display flickering and synchronization of
painting with calculation of new frames. We will first address how to get the actual painting and
application logic in sync, and then solve possible flickering.
Synchronization of Frame Calculation and Drawing
When you perform animations, you can first calculate the display content and then call repaint() in
order to paint the new frame. But how do you know that the call to paint() has finished? One
possibility would be to call serviceRepaints() , which blocks until all pending display updates
are finished. The problem with serviceRepaints() is that paint() may be called from another
thread. If the thread calling serviceRepaints() holds any locks that are required in paint() , a
deadlock may occur. Also, calling serviceRepaints() makes sense only from a thread other than
the event handling thread. Otherwise, key events may be blocked until the animation is over. An
alternative to serviceRepaints() is calling callSerially() at the end of the paint()
method. The callSerially() method lets you put Runnable objects in the event queue. The
 
Search WWH ::




Custom Search