Java Reference
In-Depth Information
LISTING 9.16
continued
//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class ReboundListener implements ActionListener
{
//--------------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
x += moveX;
y += moveY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y <= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
}
The actionPerformed method of the listener updates the current x and y coor-
dinate values, then checks to see if those values cause the image to “run into” the
edge of the panel. If so, the movement is adjusted so that the image will make
future moves in the opposite direction horizontally, vertically, or both. Note that
this calculation takes the image size into account.
The speed of the animation in this program is a function of two factors: the
pause between the action events and the distance the image is shifted each time.
In this example, the timer is set to generate an action event every 20 milliseconds,
and the image is shifted 3 pixels each time it is updated. You can experiment with
these values to change the speed of the animation. The goal should be to create
the illusion of movement that is pleasing to the eye.
 
Search WWH ::




Custom Search