by Dinesh Thakur

The class that is used to draw rectangles and squares is the Rectangle2D. The constructor specifies the first two parameters of the corner position upper left relative to the coordinate system of the window.

These four parameters can be specified using float or double values, using for this builders Rectangle2D. Float() and Rectangle2D. Double() respectively.This possibility to construct geometric figures using coordinates in float or double is a constant that is repeated in all the shapes. A rectangle can use the fill method of the java.awt.Graphics2D class. Following is at able that lists some of the Constructors and methods of Rectangle2D class:

Constructors and Methods

Description

Rectangle2D.Double ()

Creates a Rectangle2D with a size of (0, 0) at a location of (0, 0).

Rectangle2D.Double (double X, double Y, double W, double H)

Creates a Rectangle2D with a size of (W, H) at location (X, Y)

Rectangle2D.Float ()

Creates a Rectangle2D with a size of (0, 0) at a location of (0, 0).

Rectangle2D.Float (float X, float Y, float W, float H)

Creates a Rectangle2D with a size of (W, H) at location (X, Y)

contains (double X, double Y)

Returns true if the point (X, Y) is within the rectangle.

contains (double X, double Y, double W, double H)

Returns true if the rectangle (X, Y, W, H) is entirely within the rectangle.

intersects (double X, double Y, double W, double H)

Returns true if the rectangle (X, Y, W, H) intersects the rectangle.

intersectsLine (double X1, double Y1, double X2, double Y2)

setRect (double X, double Y, double W, double H)

Returns true if the line from (X1, Y1) to (X2, Y2) intersects the rectangle.

Sets the location and size of the rectangle.

 

import java.applet.Applet;

import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.image.*;
public class DrawRectangle2DExample extends Applet {
public static void main(String[] args) {
Frame Draw2DRect = new Frame("Draw 2D Rectangles Example");
Draw2DRect.setSize(350, 250);
Applet DrawRectangle2DExample = new DrawRectangle2DExample();
Draw2DRect.add(DrawRectangle2DExample);
Draw2DRect.setVisible(true);
Draw2DRect.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
      }
    });
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.setFont(new Font("Arial",Font.BOLD,14));
    g.drawString("Draw 2D Rectangles Example", 50, 40);
    g.setFont(new Font("Arial",Font.BOLD,10));
    g.drawString("http://ecomputernotes.com", 200, 205);
                super.paint(g);
                Graphics2D G2D = (Graphics2D)g;
                G2D.setColor(Color.blue);
                G2D.setStroke(new BasicStroke(3.0f));
                Rectangle2D Rect2D = new Rectangle2D.Float(100.0f, 75.0f, 50.0f, 100.0f);
                G2D.draw(Rect2D);
  }
}
 

Rectangle2D Java Example