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 (wxh). 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????
}
}

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".


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
}

鉴于您目前的实施情况:

    public boolean contains(Rectangle2D r)
{
    return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
链接地址: http://www.djcxy.com/p/83246.html

上一篇: 在鼠标点击中使用getX()getY()

下一篇: 实现布尔值包含Shape接口的(Rectangle2D r)方法