Java tutorial
//package com.java2s; import java.awt.Point; import java.awt.Rectangle; public class Main { /** * Returns the most reasonable position for the specified rectangle to be placed at so as to * maximize its containment by the specified bounding rectangle while still placing it as near * its original coordinates as possible. * * @param rect the rectangle to be positioned. * @param bounds the containing rectangle. */ public static Point fitRectInRect(Rectangle rect, Rectangle bounds) { // Guarantee that the right and bottom edges will be contained and do our best for the top // and left edges. return new Point(Math.min(bounds.x + bounds.width - rect.width, Math.max(rect.x, bounds.x)), Math.min(bounds.y + bounds.height - rect.height, Math.max(rect.y, bounds.y))); } }