Santosh Hegde -4 years ago 68

Java Question

I want to draw a rectangle with 4 points

`A(16,14) B(12,18) C(8,14) D(12,10)`

`P(12,11)`

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);`

bounds.add(12, 18);

bounds.add(8, 14);

bounds.add(12, 10);

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
rect.add(16, 14);
rect.add(12, 18);
rect.add(12, 10);
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);
rect.add(p1);
rect.add(p2);
rect.add(p3);
rect.add(p4);
return rect;
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added