Software & Finance





Java Graphics - Draw Polygon using drawPolygon





I have given here Java Graphics program to draw a Polygon using drawPolygon function.

 

 

Source Code


import java.lang.*;
import java.util.*;
import java.util.List;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class DrawPolygon extends Frame {

  public Polygon mypolygon = new Polygon();
    
  public void paint(Graphics g) {
     Graphics2D ga = (Graphics2D)g;
     ga.setPaint(Color.red);
     ga.drawPolygon(mypolygon);
     ga.setPaint(Color.green);
  }
      
  public static void main(String args[]) {
     List< Integer > srcpoints = new ArrayList< Integer >();
     srcpoints.add(100);srcpoints.add(100);
     srcpoints.add(75);srcpoints.add(75);
     srcpoints.add(150);srcpoints.add(100);
     srcpoints.add(75);srcpoints.add(125);
     srcpoints.add(srcpoints.get(0));
     srcpoints.add(srcpoints.get(1));
     
     DrawPolygon frame = new DrawPolygon();
     for(int i = 0; i < srcpoints.size(); i++)
     {
         int x = srcpoints.get(i++);
         int y = srcpoints.get(i);
         frame.mypolygon.addPoint(x, y);
     }
     
     frame.addWindowListener(
      new WindowAdapter()
      {
         public void windowClosing(WindowEvent we)
         {
            System.exit(0);
         }
      }
     );
     
   frame.setSize(400, 400);
   frame.setVisible(true);
  }
}

/***
      Enter Number of points: 4
      Enter x[1]: 100
      Enter y[1]: 100
      Enter x[2]: 150
      Enter y[2]: 100
      Enter x[3]: 150
      Enter y[3]: 150
      Enter x[4]: 100
      Enter y[4]: 150
***/ 

Output