2012-04-24 54 views
3

這裏是我的Java問題:實現布爾包含Shape接口的(矩形R)法

我Circle類實現了Shape接口,因此它必須實現所有所需的方法。我有一個方法boolean contains(Rectangle2D r)「測試Shape的內部是否完全包含指定的Rectangle2D」。現在,Rectangle2D是一個抽象類,它沒有提供任何方法來獲得矩形的角點座標。更精確地說:「Rectangle2D類描述了一個由位置(x,y)和維(wxh)定義的矩形,該類只是存儲2D矩形的所有對象的抽象超類,座標的實際存儲表示留給子類「。

那麼我該如何解決這個問題呢?

請在下面找到我的代碼的一部分:

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???? 
} 
} 
+0

這功課嗎?但是你沒有標籤槽... – 2012-04-24 14:54:37

+0

你在使用什麼開發環境?因爲缺乏關於某個特定類的知識不應該成爲一個問題,因爲它應該向你展示'r'的可用方法,當你鍵入'r.' – weston 2012-04-24 15:01:14

回答

4

Rectangle2D繼承RectangularShapegetMaxX, getMaxY, getMinX, getMinY。所以你可以得到角落的座標。

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

請參閱 「從類java.awt.geom.RectangularShape繼承的方法」。

+0

@HovercraftFullOfEels是的,但不會創建一個新的矩形對象嗎?我認爲它不公開內部邊界矩形。然後你仍然需要在該對象上調用'getX()''getY()''getWidth()'和'getHeight()'來測試4個座標。 – weston 2012-04-24 15:09:28

+1

是的,你是對的。我正在刪除我的無用評論 – 2012-04-24 15:11:59

1

使用PathIterator。將努力爲所有凸形狀

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 
} 
0

鑑於你目前執行的:

public boolean contains(Rectangle2D r) 
{ 
    return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight()); 
} 
0

可以擴展Ellipse2D.Double設置寬度和高度爲相同的值。

Ellipse2D.Double(double x, double y, double w, double h) 

然後可以使用其contains方法傳遞給它Rectangle2D拐角(你有左上角X和Y以及寬度和高度,因此在計算的角部是微不足道的)。 true返回爲contains適用於所有矩形的角落表示該圓形包含矩形