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.
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);
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
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.
}
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();
}
}
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.