Search code examples
javajavafxrectanglesscene

"Rectangle cannot be converted to bounds" using rectangle.intersect()?


So I am passing double values from a rectangle to see if it intersects with a different rectangle. I pass the attribute values (x, y, w, h) as arguments to the function, then create a rectangle within it and set the argument as its attributes. I then I test it using the rectangle.intersects(rect) to see if they overlap. The code is below.

THE PROBLEM: The line inputRectangle.intersects(scannedRectangle); is giving an error that says "Incompatible types: Rectangle cannot be converted to bounds.

A Google and SO search had no results for that error.

How am I going about this incorrectly? Thanks

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

}

NOTE: I simplified the code somewhat. But no matter how I change the code, the scannedRectangle segment in the function is giving that error.


Solution

  • javafx.scene.shape.Rectangle is a Node. Since you're not using those objects as parts of a scene, you're better off using javafx.geometry.Rectangle2D to check for intersections. This class does not extend Node and it allows you to check 2 Rectangle2Ds for intersection.

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