Java Graphics How to - Add, subtract, intersect, exclusiveOr shapes








Question

We would like to know how to add, subtract, intersect, exclusiveOr shapes.

Answer

 // w ww  .  j a  v  a 2  s .c o  m


import java.awt.Rectangle;
import java.awt.geom.Area;

public class Main {
  public static void main(String[] args) {
    Area shape = new Area(new Rectangle(1, 1, 1, 1));
    shape.add(new Area(new Rectangle(1, 1, 1, 1)));
    shape.subtract(new Area(new Rectangle(1, 1, 1, 1)));
    shape.intersect(new Area(new Rectangle(1, 1, 1, 1)));
    shape.exclusiveOr(new Area(new Rectangle(1, 1, 1, 1)));
    
    System.out.println(shape.intersects(new Rectangle(1, 1, 1, 1)));
  }
}

The code above generates the following result.