# Java: Polygons

A `java.awt.Polygon` can be used to represent a polygon as a set of points for the vertexes. A polygon object can be drawn or filled, by methods in the `java.awt.Graphics` class.

## Creating a Polygon by adding points

Use the `addPoint(int xcoord, int ycoord)` method to add one point to the polygon. You may add as many points as you wish.

    Polygon poly = new Polygon();
    . . .
    // Make a triangle
    poly.add(100, 100);
    poly.add(150, 150);
    poly.add(50,  150);

## Creating a Polygon from arrays of coordinates

An alternative way to create a Polygon is from arrays of x and y coordinates. For example,

    int[]x = new int[3];
    int[]y = new int[3];
    int n;  // count of points
    . . .
    // Make a triangle
    x[0]=100; x[1]=150; x[2]=50;
    y[0]=100; y[1]=150; y[2]=150;
    n = 3;
    . . .
    Polygon myTri = new Polygon(x, y, n);  // a triangle

## To draw or fill a Polygon

Use the Graphics methods `g.drawPolygon(p)` or `g.fillPolygon(p)` to draw or fill a polygon, where p is the polygon. For example,

    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // paint background
        g.fillPolygon(myTri);     // fills triangle above.
    }

## To check if a point is in a Polygon

One useful feature of Polygons is that it's easy to check if a point is inside or outside a polygon. Polygon's `contains(int x, int y)` method returns `true` if the point at (x,y) is inside the Polygon. For example, you may want to know if a mouse click is inside a Polygon.

    public void mouseClicked(MouseEvent e) {
        if (myPoly.contains(e.getX(), e.getY()) {
            inside = true;
            repaint();
        }
    }

## Translating

A polygon can be moved in the x and y directions with

    poly.translate(xdisp, ydisp);

where xdisp is how far to move it in the x direction from its current location, and ydisp gives the corresponding y distance. The coordinates of the polygon are changed after a move.