1 /* MovableRectangle.java */ 2 3 import java.awt.*; 4 5 public class MovableRectangle extends MovableObject { 6 7 // Instance variables: 8 protected int w, h; // width and height 9 10 // Constructor: 11 public MovableRectangle( int new_x, int new_y, int new_w, int new_h ) { 12 // Invoke the constructor of the superclass MovableObject: 13 super( new_x, new_y ); 14 w = new_w; h = new_h; 15 } 16 17 // Implement MovableObject.paint( Graphics ): 18 public void paint( Graphics g ) { 19 g.setColor( color ); 20 g.fillRect( x, y, w, h ); 21 } 22 23 // Implement MovableObject.checkBoundary( Rectangle ): 24 public void checkBoundary( Rectangle r ) { 25 // Calculate new location: 26 int nx = x + dx, ny = y + dy; 27 // Check if new location out of bounds: 28 if ( (nx < r.x) || (nx + w > r.x + r.width) ) dx = -dx; 29 if ( (ny < r.y) || (ny + h > r.y + r.height) ) dy = -dy; 30 } 31 32 // Implement MovableObject.contains( int, int ): 33 public boolean contains( int some_x, int some_y ) { 34 Rectangle r = new Rectangle( x, y, w, h ); 35 return r.contains( some_x, some_y ); 36 } 37 38 } // end of MovableRectangle class 39