Boundary Checking
Here is a better approach: int dx = 1, dy = 1; public void paint( Graphics g ) { checkBounds( this.getBounds() ); square.translate( dx, dy ); square.fill( g ); }
The checkBounds(…) method reverses the direction of motion, if necessary…