Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing boolean contains(Rectangle2D r) method of Shape interface

here is my Java problem:

My Circle class implements the Shape interface and thus it must implement all the methods required. I have a problem with the method boolean contains(Rectangle2D r) that "Tests if the interior of the Shape entirely contains the specified Rectangle2D". Now, Rectangle2D is an abstract class that does not provide (to the best of my poor knowledge) any method to get the coordinates of the corners of the rectangle. To be more precise: "The Rectangle2D class describes a rectangle defined by a location (x, y) and dimension (w x h). This class is only the abstract superclass for all objects that store a 2D rectangle. The actual storage representation of the coordinates is left to the subclass".

So how can I solve this?

Please find below a part of my code:

public class Circle implements Shape
{
private double x, y, radius;

public Circle(double x, double y, double radius)
{
    this.x = x;
    this.y = y;
    this.radius = radius;
}

// Tests if the specified coordinates are inside the boundary of the Shape
public boolean contains(double x, double y)
{
    if (Math.pow(this.x-x, 2)+Math.pow(this.y-y, 2) < Math.pow(radius, 2))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Tests if the interior of the Shape entirely contains the specified rectangular area
public boolean contains(double x, double y, double w, double h)
{
    if (this.contains(x, y) && this.contains(x+w, y) && this.contains(x+w, y+h) && this.contains(x, y+h))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Tests if a specified Point2D is inside the boundary of the Shape
public boolean contains(Point2D p)
{
    if (this.contains(p.getX(), p.getY()))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Tests if the interior of the Shape entirely contains the specified Rectangle2D
public boolean contains(Rectangle2D r)
{
    // WHAT DO I DO HERE????
}
}
like image 521
stkhou Avatar asked Jun 21 '26 03:06

stkhou


2 Answers

Rectangle2D inherits getMaxX, getMaxY, getMinX, getMinY from RectangularShape. So you can get the coords of the corners.

http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/geom/Rectangle2D.html

See "Methods inherited from class java.awt.geom.RectangularShape".

like image 79
weston Avatar answered Jun 22 '26 16:06

weston


Use PathIterator. Will work for all convex shapes

PathIterator it = rectangle.getPathIterator(null);
while(!it.isDone()) {
    double[] coords = new double[2];
    it.currentSegment(coords);
    // At this point, coords contains the coordinates of one of the vertices. This is where you should check to make sure the vertex is inside your circle
    it.next(); // go to the next point
}
like image 43
mprivat Avatar answered Jun 22 '26 18:06

mprivat