Drawing a Rectangle using Java 2D Graphics API

This Java source code example shows how to draw a rectangle using the Java 2D Graphics API.
The rectangle is drawn on a JFrame but could be drawn on other AWT or Swing components as well.
All the painting work takes place in a method called paint(Graphics g). The paint method is called automatically when the JFrame is displayed so there is no need for an explicit call to the method.

First we need to cast the graphics object to a Graphics2D object, and then create an instance of the Rectangle2D class by calling the static method Float() which takes four parameters.
The parameters are the coordinates of the upper left corner (parameter 1 and 2) and the width and height of the rectangle (parameter 3 and 4).
The origin is the top left corner (with coordinates 0, 0), which means that the upper left corner of the rectangle is positioned 100 pixels from the left side and 100 pixels from the top.
The rectangle is 240 pixels wide and 160 pixels high. Finally the draw() method of the Graphics2D object is called with the Rectangle2D instance passed as argument.

This is what it looks like after drawing the rectangle using the Java 2D API:

Drawing a rectangle with the Java 2D Graphics API

This is the code of the entire JFrame class which is possible to execute by itself.

Search for more Java info on this site here:
Custom Search

Please type any questions here.