The checkBounds Method
This ensures the square stays within r: private void checkBounds( Rectangle r ) { // Compute dimensions of the square: Rectangle bb = square.getBounds(); int w = bb.width, h = bb.height; int new_x = bb.x + dx, new_y = bb.y + dy; // If square is out of bounds, reverse direction: if ( ( new_x < r.x ) || ( new_x + w > r.x + r.width ) ) dx *= -1; if ( ( new_y < r.y ) || ( new_y + h > r.y + r.height ) ) dy *= -1; }
Note: The method refers to java.awt.Rectangle!