Create polygon from GeneralPath in Java
Description
The following code shows how to create polygon from GeneralPath.
Example
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
// w ww . j a va2 s . co m
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
int x = 5;
int y = 7;
int xPoints[] = { x, 200, x, 200 };
int yPoints[] = { y, 230, 200, y };
GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
xPoints.length);
polygon.moveTo(xPoints[0], yPoints[0]);
for (int index = 1; index < xPoints.length; index++) {
polygon.lineTo(xPoints[index], yPoints[index]);
}
polygon.closePath();
g2.draw(polygon);
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.