在Rectangle中约束Rectangle

bau*_*aum 10 java rectangles

Rectangle在一个程序中使用Java的类.

我有两个Rectangle对象:

Rectangle big = new Rectangle(...);
Rectangle small = new Rectangle(...);
Run Code Online (Sandbox Code Playgroud)

矩形的具体尺寸并不重要.然而,big总是会大于small(在宽度和高度).

通常,small完全包含在内big.我可以Rectangle#contains用来验证这一点.然而,当这是不是这样,我想移动 small到内完全包含big.两个矩形的尺寸都不应改变.

例如:

矩形示例

我知道可以使用四个条件Math.maxMath.min,但是有更优雅的方式吗?

Gho*_*per 2

你可以只用Math.max和来做到这一点Math.min。尝试这样的事情:

small.setLocation(
    Math.max(Math.min(small.getX(),big.getX() - small.getWidth()),big.getX()),
    Math.max(Math.min(small.getY(),big.getY() - small.getHeight()),big.getY())
);
Run Code Online (Sandbox Code Playgroud)

不过,您必须考虑可读性。