 Santosh Hegde -4 years ago 68
Java Question

# How to define java.awt.Rectangle using 4 points?

I want to draw a rectangle with 4 points

`A(16,14) B(12,18) C(8,14) D(12,10)`
and want to check the point
`P(12,11)`
is present inside the rectangle or not.

Is it possible to achieve this using
`java.awt.Rectangle`
?

I tried below code and not working as expected.

``````Rectangle bounds = new Rectangle(16, 14);

System.out.println(bounds.contains(1,1)); // printing true which is not right
`````` Sweeper

Creating a rectangle with 4 points is quite easy.

First, you need to find the point with the smallest x and y. Assign the smallest x and y values to `originX` and `originY` respectively. Then, create a rectangle with the arguments `(originX, originY, 0, 0)`. After that, call `add` three times to add the other points.

In your case, this would work:

``````Rectangle rect = new Rectangle(8, 14, 0, 0); // 8 and 14 are the smallerst x and y
System.out.println(rect.contains(1,1)); // false
``````

I have written a method for you:

``````public static Rectangle createRectangeWithPoints(Point p1, Point p2, Point p3, Point p4) {
int originX = (int)Math.min(p1.getX(), Math.min(p2.getX(), Math.min(p3.getX(), p4.getX())));
int originY = (int)Math.min(p1.getY(), Math.min(p2.getY(), Math.min(p3.getY(), p4.getY())));
Rectangle rect = new Rectangle(originX, originY, 0, 0);