You're viewing this page with a browser that doesn't understand the APPLET tag. If you were using a Java-enabled browser that understood the APPLET tag, you'd see Scrolling Text here.

In last example, we can see two rectangle moving on the screen. But these two rectangle will go outside the boundry eventually. We add a method here to check if this object hit the boundry. When it hit the boundry, we change the object's moving direction. Now, you can see two rectangle bouncing inside the boundry.

Add a Boundry Checking Method

We add a boundry check mothod in mPoint as follow:

  public void checkBoundry(Rectangle rect) {
    int nx = x+dx; /* caculate new location */
    int ny = y+dy;
    /* check if new location out of boundry */
    if ( (nx = rect.x+rect.width) ) dx = -dx;
    if ( (ny = rect.y+rect.height) ) dy = -dy;
  }

The boundry check in mRectangle is slightly different. So we redefine the checkBoundry in mRectangle.

  public void checkBoundry(Rectangle rect) {
    /* overwrite the mPoint's checkBoundry */
    /* the rectangle's checkBoundry is different */
    int nx = x+dx;
    int ny = y+dy;
    if ( (nx = rect.x+rect.width) ) dx = -dx;
    if ( (ny = rect.y+rect.height) ) dy = -dy;
  }
Class Hierarchy:
Applet --- Test
mPoint --- mRectangle

JAVA Source Code
1. Test.java (Main Program)
1. mPoint.java (Movable Point)
1. mRectangle.java (Movable Rectangle)