public static @NotNull Point findNearestPointOnBorder(@NotNull Rectangle rect, @NotNull Point p) {
    final int x0 = rect.x;
    final int y0 = rect.y;
    final int x1 = x0 + rect.width;
    final int y1 = y0 + rect.height;
    double distance = -1;
    Point best = null;
    final Point[] variants = {new Point(p.x, y0), new Point(p.x, y1), new Point(x0, p.y), new Point(x1, p.y)};
    for (Point variant : variants) {
      final double d = variant.distance(p.x, p.y);
      if (best == null || distance > d) {
        best = variant;
        distance = d;
      }
    }
    return best;
  }
public static @NotNull Point findNearestPointOnBorder(@NotNull Rectangle rect, @NotNull Point p)