Java Graphics Draw Polygons Applets

Java Graphics Draw Polygons Applets


A polygon is a closed figure with many lines joined one to another. The ending point of one line is the starting point to another line and finally the last point is joins with the first point.

java.awt.Graphics class comes with two methods and one constructor to draw polygons.

  1. void drawPolygon(int x[], int y[], int numOfPoints): Draws an outline polygon as per the coordinates specified in the x[] and y[] arrays. The numOfPoints gives the number of points (or to say, number of elements in the array) to join.
  2. void fillPolygon(int x[], int y[], int numOfPoints): Draws a solid polygon as per the coordinates specified in the x[] and y[] arrays. The numOfPoints gives the number of points (or to say, number of elements in the array) to join.
  3. Polygon(int x [], int y [], int numOfPoints): This constructor draws an outline polygon as per the coordinates specified in the x[] and y[] arrays. The numOfPoints gives the number of points to join.

All the above methods are used to draw polygons.

4 styles of drawing polygon are given.

  1. Using drawPolygon() with arrays.
  2. Using java.awt.Polygon class.
  3. Using drawLine() method.
  4. Using addPoint() method.

1st style: Using drawPolygon() with arrays

Here, two arrays comprising of x-coordinates and y-coordinates are created. These two arrays are passed to drawPolygon() method of Graphics class.

File Name: DrawingPolygons.java

File Name: DP.html

Java Graphics Draw Polygons Applets 

Two arrays of x and y are created each with 5 elements. The array objects x and y are passed to drawPolygon() method with 5 points (marked by elements) to join. Alternatively, you can join 3 or 4 points also that joins first 3 or 4 becoming a triangle and quadrilateral. Attempting to join 6 points, which do not exist, throws ArrayIndexOutOfBoundsException.

2nd style: Using java.awt.Polygon class

The above polygon can also be obtained with Polygon constructor as follows.

All the earlier programs like drawing rectangles are illustrated with Frame. Now let us go for applet. Applet includes init(), start() and paint() methods etc. The migration steps from graphics application to applet are available in “Java AWT Radio Buttons – Applet GUI“.

2 thoughts on “Java Graphics Draw Polygons Applets

Leave a Reply

Your email address will not be published. Required fields are marked *