Rectangle

The Rectangle class encapsulates x and y coordinates and width and height (Point and Dimension information) within a single object. It is often used by methods that return a rectangular boundary as a single object: for example, Polygon.getBounds(), Component.getBounds(), and Graphics.getClipBounds(). Like Point, the Rectangle class is not a visual object and does not represent a rectangle on the screen; ironically, drawRect() and fillRect() don't take Rectangle as an argument.

Rectangle Methods

Variables

The four public variables available for Rectangle have the same names as the public instance variables of Point and Dimension. They are all accessible directly or through use of the getBounds() method.

Constructors

The following seven constructors create Rectangle objects. When you create a Rectangle, you provide the location of the top left corner, along with the Rectangle's width and height. A Rectangle located at (0,0) with a width and height of 100 has its bottom right corner at (99, 99). The Point (100, 100) lies outside the Rectangle, since that would require a width and height of 101.

Shaping and sizing
import java.awt.Rectangle;
public class rect {
 public static void main (String[] args) {
 Rectangle r = new Rectangle (100, 100, 200, 200); System.out.println (r); r.grow (50, 75); System.out.println (r); r.grow (-25, -50); System.out.println (r);
}
} 

This program produces the following output:

java.awt.Rectangle[x=100,y=100,width=200,height=200] java.awt.Rectangle[x=50,y=25,width=300,height=350] java.awt.Rectangle[x=75,y=75,width=250,height=250] 
Intersections

Figure 2.13: Rectangle intersection

[Graphic: Figure 2-13]

Figure 2.14: Rectangle union

[Graphic: Figure 2-14]Miscellaneous methods

java.awt.Rectangle[x=100,y=200,width=300,height=400]