With a little clever use of Area
you can get the Graphics2D
API to do it for you.
Basically, I create an Area
that is the result of an exclusiveOR operation on the two rectangles. I then subtract this from an Area
that is the result of adding the two rectangles together

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Area;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class OverlappingRectangles {
public static void main(String[] args) {
new OverlappingRectangles();
}
public OverlappingRectangles() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle r1 = new Rectangle(0, 0, 150, 150);
Rectangle r2 = new Rectangle(50, 50, 150, 150);
g2d.setColor(Color.RED);
g2d.fill(r1);
g2d.setColor(Color.BLUE);
g2d.fill(r2);
Area a1 = new Area(r1);
a1.exclusiveOr(new Area(r2));
Area a2 = new Area(r2);
a2.add(new Area(r1));
a2.subtract(a1);
g2d.setColor(Color.GREEN);
g2d.fill(a2);
g2d.dispose();
}
}
}