Here you can find the source of rectDistance(final Rectangle r, final Rectangle q)
public static int rectDistance(final Rectangle r, final Rectangle q)
//package com.java2s; //License from project: Apache License import java.awt.Rectangle; public class Main { public static int rectDistance(final Rectangle r, final Rectangle q) { if (rectOverlaps(r, q)) { return 0; }//from ww w .j a va 2 s .c om int r_x0 = r.x; int r_x1 = r.x + r.width; int r_y0 = r.y; int r_y1 = r.y + r.height; int q_x0 = q.x; int q_x1 = q.x + q.width; int q_y0 = q.y; int q_y1 = q.y + q.height; int d = 0; if (r_x0 > q_x1) { d += (r_x0 - q_x1) * (r_x0 - q_x1); } else if (q_x0 > r_x1) { d += (q_x0 - r_x1) * (q_x0 - r_x1); } if (r_y0 > q_y1) { d += (r_y0 - q_y1) * (r_y0 - q_y1); } else if (q_y0 > r_y1) { d += (q_y0 - r_y1) * (q_y0 - r_y1); } return (int) Math.sqrt((double) d); } public static boolean rectOverlaps(final Rectangle r, final Rectangle q) { int x0 = r.x; int x1 = r.x + r.width; int y0 = r.y; int y1 = r.y + r.height; int q_x0 = q.x; int q_x1 = q.x + q.width; int q_y0 = q.y; int q_y1 = q.y + q.height; return x0 <= q_x1 && y0 <= q_y1 && q_x0 <= x1 && q_y0 <= y1; } }