The Rectangle Class - Java 2D Graphics

Java examples for 2D Graphics:Rectangle

Introduction

Rectangle class represents a rectangle.

Rectangle class is in the java.awt package.

A Rectangle is defined by three properties:

  • (x, y) coordinates of the upper-left corner
  • Width
  • Height

You can create an object of the Rectangle class by specifying different combinations of its properties.

Create a Rectangle object whose upper-left corner is at (0, 0) with width and height as zero

import java.awt.Rectangle;

public class Main {
  public static void main(String[] argv) throws Exception {
    Rectangle r = new Rectangle();
  }
}

Create a Rectangle object from a Point object with its width and height as zero

import java.awt.Point;
import java.awt.Rectangle;

public class Main {
  public static void main(String[] argv) throws Exception {
    Rectangle r = new Rectangle(new Point(10, 10));
  }
}

Create a Rectangle object from a Point object and a Dimension object

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;

public class Main {
  public static void main(String[] argv) throws Exception {
    Rectangle r = new Rectangle(new Point(10, 10), new Dimension(200, 100));
  }
}

Create a Rectangle object by specifying its upper-left corner's coordinate at (10, 10) and width as 200 and height as 100.

import java.awt.Rectangle;

public class Main {
  public static void main(String[] argv) throws Exception {
    Rectangle r = new Rectangle(10, 10, 200, 100);
  }
}

Related Tutorials