"矩形不能转换为边界"使用rectangle.intersect()?

时间:2016-11-09 11:30:42

标签: java javafx rectangles scene

所以我从矩形传递双值以查看它是否与不同的矩形相交。我将属性值(x,y,w,h)作为参数传递给函数,然后在其中创建一个矩形并将参数设置为其属性。然后,我使用rectangle.intersects(rect)对其进行测试,看看它们是否重叠。代码如下。

问题inputRectangle.intersects(scannedRectangle);行的错误是"Incompatible types: Rectangle cannot be converted to bounds

Google和SO搜索没有出现该错误的结果。

我怎么会错误地解决这个问题?谢谢

import javafx.scene.shape.Rectangle;
-----------^^^^^^^^^^^^^^^^------------

public boolean isIntersectingNode(double inputX, double inputY, double inputWidth, double inputHeight)
{

    Rectangle inputRectangle = new Rectangle(inputX, inputY, inputWidth, inputHeight);
    double newX = 20, newY = 20, newW = 20, newH = 20;

    Rectangle scannedRectangle = new Rectangle(newX, newY, newW, newH);

    return inputRectangle.intersects(scannedRectangle);  <<<<<<<ERROR HERE

}

注意:我稍微简化了代码。但无论我如何更改代码,函数中的scannedRectangle段都会给出错误。

3 个答案:

答案 0 :(得分:4)

javafx.scene.shape.RectangleNode。由于您没有将这些对象用作场景的一部分,因此最好使用javafx.geometry.Rectangle2D来检查交叉点。此类不会扩展Node,它允许您检查2 Rectangle2D的交集。

public boolean isIntersectingNode(double inputX,
                                  double inputY,
                                  double inputWidth,
                                  double inputHeight) {

    Rectangle2D inputRectangle = new Rectangle2D(inputX, inputY, inputWidth, inputHeight);
    double newX = 20, newY = 20, newW = 20, newH = 20;

    Rectangle2D scannedRectangle = new Rectangle2D(newX, newY, newW, newH);

    return inputRectangle.intersects(scannedRectangle);
}

答案 1 :(得分:2)

请注意,intersects()需要类型为Bounds的对象作为参数。 Rectangle不会从Bounds继承,因此无法在此处使用。您可能想尝试使用getBounds...()方法之一来获取然后相交的边界。

答案 2 :(得分:1)

错误是因为Node.intersects接受Bounds个对象作为输入参数:

public boolean intersects(Bounds localBounds)
  

如果给定的边界(在本地坐标中指定),则返回true   此节点的空间)与此节点的形状相交。

另一方面,在isIntersectingNode方法中,您不会将Rectangle实例添加到场景图中,因此无法检查交叉点,因为它们没有坐标空间。

作为一种解决方案,您可以使用原始Rectangle对象,该对象附加到场景图并执行,例如:

 rect.getBoundsInParent().intersects(x, y, w, h);