Java AWT Graphics draw Polygon

Description

Java AWT Graphics draw Polygon


// Drawing polygons.
import java.awt.Graphics;
import java.awt.Polygon;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  // draw polygons and polylines
  @Override/*  ww w  .  j  av a2 s. c  o m*/
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // draw polygon with Polygon object
    int[] xValues = { 2, 440, 50, 430, 20, 115 };
    int[] yValues = { 5, 50, 640, 80, 480, 610 };
    Polygon polygon1 = new Polygon(xValues, yValues, 6);
    g.drawPolygon(polygon1);

    // draw polylines with two arrays
    int[] xValues2 = { 70, 90, 10, 80, 170, 65, 160 };
    int[] yValues2 = { 100, 10, 110, 11, 130, 110, 90 };
    g.drawPolyline(xValues2, yValues2, 7);

    // fill polygon with two arrays
    int[] xValues3 = { 120, 140, 50, 190 };
    int[] yValues3 = { 410, 170, 80, 60 };
    g.fillPolygon(xValues3, yValues3, 4);

    // draw filled polygon with Polygon object
    Polygon polygon2 = new Polygon();
    polygon2.addPoint(165, 135);
    polygon2.addPoint(175, 50);
    polygon2.addPoint(20, 10);
    polygon2.addPoint(200, 220);
    polygon2.addPoint(10, 180);
    g.fillPolygon(polygon2);
  }

  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("Drawing Polygons");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Main Main = new Main();
    frame.add(Main);
    frame.setSize(280, 270);
    frame.setVisible(true);
  }
}



PreviousNext

Related