Issue
I have the following code which makes a basic Pane with a Rectangle inside it:
public class Canvas extends Pane{
public Canvas() {
Rectangle rect = new Rectangle(50,50, Color.GOLD);
this.setBackground(new Background(new BackgroundFill(Color.INDIANRED,new CornerRadii(0),new Insets(0))));
this.setPrefSize(200, 200);
rect.setX((this.getMaxWidth()/2) + (rect.getWidth()));
rect.setY((this.getMaxHeight()/2) + (rect.getHeight()));
this.getChildren().add(rect);
}
I already tried a few things to get the center of the triangle at the center of the Pane (one example in the above code), but because in JavaFX the X and Y coordinates of a Rectangle represent the top left corner it has made it more difficult to center it within my pane. I am very bad at maths and dont know the correct formula to achieve this. How can i get the center of my Rectangle to align with the center of my Pane? Without using Stackpane etc...
Solution
You want to align the midpoint of the Rectangle with the midpoint of the Pane.
You have to find the midpoint of the pane (x and y), and the rectangle (x and y).
// Find the midpoint of the Pane.
// x midpoint
float xPaneMidpoint = pane.width / 2
// y midpoint
float yPaneMidpoint = pane.height/ 2
You then move the Rectangle to the position of the midpoint of the Pane, then offset it by half of its size
// Take the midpoint of the pane, and move the rectangle to that point.
// Then offset it by half its width/height
rectangle.setX( xPaneMidpoint - (rectangle.width / 2));
rectangle.setX( yPaneMidpoint - (rectangle.height/ 2));
Answered By - Atom