JavaFX Rectangle overlap check
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; public class Main extends Application { @Override/* www . jav a 2 s . c om*/ public void start(Stage primaryStage) { // Create a pane and a vbox Pane pane = new Pane(); VBox vBox = new VBox(20); vBox.setPadding(new Insets(10, 5, 5, 10)); Rectangle r1 = getRectangle(12, 23, 56, 76); Rectangle r2 = getRectangle(43, 45, 78, 90); // Test if rectangles contain or overlap each other String output = " "; if (contains(r1, r2) || contains(r2, r1)) output += "One rectangle is contained in another "; else if (overlaps(r1, r2)) output += "The rectangles overlap "; else output += "The rectangles do not overlap "; // Add rectangles to pane pane.getChildren().addAll(r1, r2); // Place nodes in vbox vBox.getChildren().addAll(pane, new Text(20, 0, output)); // Create a scene and place it in the stage Scene scene = new Scene(vBox); primaryStage.setTitle("java2s.com"); primaryStage.setScene(scene); primaryStage.show(); } /** Returns a rectangle with specified center coordinates, width, height. */ private Rectangle getRectangle(int x1, int y1, int x2, int y2) { Rectangle r = new Rectangle(x1, y1, x2, y2); r.setFill(Color.WHITE); r.setStroke(Color.BLACK); return r; } /** Returns true if one rectangle is inside the other */ public boolean contains(Rectangle r1, Rectangle r2) { return r2.getY() + r2.getHeight() <= r1.getY() + r1.getHeight() && r2.getX() + r2.getWidth() <= r1.getX() + r1.getWidth() && r2.getX() > r1.getX() && r2.getY() > r1.getY(); } /** Returns true if the specified rectangles overlap */ public boolean overlaps(Rectangle r1, Rectangle r2) { return getDistance(r1.getX(), r2.getX() + r2.getWidth()) < r1.getWidth() + r2.getWidth() && getDistance(r1.getY(), r2.getY() + r2.getHeight()) < r1.getHeight() + r2.getHeight(); } private double getDistance(double p1, double p2) { return Math.sqrt(Math.pow(p2 - p1, 2)); } }