LBecker LBecker - 2 months ago 48
Java Question

Java how to draw and fill a Polygon which has holes

I am currently trying to draw and fill a Polygon which has a hole in it in Java. Normally this would not be a big problem, since I would draw the exterior ring and then draw the interior ring with the color of the background.

But the problem is, that the polygon is displayed above a image which should be "seen" through the hole.

I am writing the code in Java and am using JTS Topology Suite for my geometry data.

This is my current code, which just paints the border and fills the polygon with a color.

private void drawPolygon(com.vividsolutions.jts.geom.Polygon gpoly, Color color, Graphics2D g2d){

java.awt.Polygon poly = (java.awt.Polygon)gpoly;

for(Coordinate co : gpoly.getExteriorRing().getCoordinates() {
poly.addPoint(co.x, co.y);


Sadly java.awt.Polygon does not support Polygons with holes.

  • Use the Polygon as the basis for an Area (e.g. called polygonShape).
  • Create an Ellipse2D for the 'hole', then establish an Area for it (ellipseShape).
  • Use Area.subtract(Area) something like:

    Area polygonWithHole = polygonShape.subtract(ellipseShape);