Java Graphics Draw Polygons Applets


3rd style: Using drawLine() method.

Each and every line of the polygon is drawn separately (with drawLine()) while attaching end-points of one line to the starting points of another. If this is not done properly, you get a open polygon figure. This is a tedious approach compared to other 3 styles.

import java.awt.*;
public class Style3Polygon extends Frame
{
  public Style3Polygon()
  {
    setTitle("Polygons by S N Rao");
    setSize(250, 350);
    setVisible(true);
  }
  public void paint(Graphics g)   
  {
    g.drawLine(30, 50, 170, 110);
    g.drawLine(170, 110, 190, 220); 
    g.drawLine(190, 220, 150, 320); 
    g.drawLine(150, 320, 30, 50);  
  }
  public static void main(String args[])
  {
    new Style3Polygon();
  }
}

Java Graphics Draw Polygons Applets

Observe the line coordinates carefully. One line x1 and y1 coordinates are another line's x2, y2. Again starting line x1, y1 are last line's x2, y2; else, an open figure will be obtained.

4th style: Using addPoint() method.

Here, we use addPoint() method of Polygon class. addPoint() method takes a pair of coordinates that becomes automatically the vertex of the polygon. drawPolygon() method takes care of joining the first vertex with the last vertex.

Supporting method of Polygon class

  • void addPoint(int x, int y): drawPolygon() mehod joints all the points of x and y specified in each addPoint() method.
import java.awt.*;
public class Style4Polygon extends Frame
{
  public Style4Polygon()
  {
    setTitle("Polygons by S N Rao");
    setSize(400, 300);
    setVisible(true);
  }
  public void paint(Graphics g)   
  { 
    Polygon p1 = new Polygon();
    p1.addPoint(40,50);
    p1.addPoint(160,150);
    p1.addPoint(220,140);
    p1.addPoint(175,270);
    p1.addPoint(80,90);
    g.drawPolygon(p1);
  }
  public static void main(String args[])
  {
    new Style4Polygon();
  }
}

Java Graphics Draw Polygons Applets

Now, you need not worry about the coordination of each x and y values. Give any values for each addPoint() method. The points are joined by the Polygon class implicitly.

One more program on graphics with applets is available in "Drawing Circles (Graphics with Applets)".

Note: Knowledge of "applets" is required to do with this program.

Note: In applet, window closing does not require extra code. It is implicit.

4 thoughts on “Java Graphics Draw Polygons Applets”

Leave a Comment

Your email address will not be published.