LISTING 4: The Extended Project's displayImage() Method

private void displayImage(Graphics g)

// image goes boing

{

if (!m_fAllLoaded)

return;

// erase previous image

g.clearRect(m_nImgXprev, m_nImgYprev,

* m_nImgWidth, m_nImgHeight);

// Draw Image at next location in applet

//---------------------------------------

g.drawImage(m_Images[m_nCurrImage],

* m_nImgX, m_nImgY, null );

// next (x,y) location for image

// original code:

// (size().width - m_nImgWidth) / 2,

// (size().height - m_nImgHeight) / 2, null);

travelImage();

// determine next location for image

}

private void travelImage()

{

m_nImgXprev = m_nImgX;

m_nImgYprev = m_nImgY;

// save previous location

// calculate vector if we hit boundary

// of applet

m_incX = checkForTurnaround(m_nImgX,

* m_nImgWidth, m_rng.width, m_incX);

m_incY = checkForTurnaround(m_nImgY,

* m_nImgHeight, m_rng.height, m_incY);

m_nImgX += m_incX;

m_nImgY += m_incY;

// setup to next location to draw image

}

private int checkForTurnaround(int pos,

* int wid, int max, int inc)

{

double rd = 0;

// random number

int nextMax = pos + wid + inc + 1;

// next max of image on this side

int nextMin = pos + inc - 1;

// next min of image on this side

// check for out of bounds in this

// direction

if ((nextMax>max) || (nextMin<0))

{ // if so recalulate the vector in this // direction

rd = Math.random();

// new random number

inc = (int)(rd * m_maxSpeed + 0.5);

// % of max speed rounded up

if (inc<m_minSpeed) // too slow?

inc += m_minSpeed; // no slow mo!

if (nextMax>max)

// if had been moving positive

inc = (-inc);

// turn around; use negative

// increment

}

returninc;
// return the speed increment

}