JavaFX 在窗格中居中矩形
JavaFX center a Ractangle within a Pane
我有以下代码,它制作了一个基本的窗格,里面有一个矩形:
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);
}
我已经尝试了一些方法来使三角形的中心位于窗格的中心(上面代码中的一个示例),但是因为在 JavaFX 中,矩形的 X 和 Y 坐标表示左上角它使它更难在我的窗格中居中。我的数学很差,不知道实现此目标的正确公式。
如何让矩形的中心与窗格的中心对齐?
不使用 Stackpane 等...
您想将矩形的中点与窗格的中点对齐。
您必须找到窗格(x 和 y)和矩形(x 和 y)的中点。
// Find the midpoint of the Pane.
// x midpoint
float xPaneMidpoint = pane.width / 2
// y midpoint
float yPaneMidpoint = pane.height/ 2
然后将矩形移动到窗格的中点位置,然后将其偏移其大小的一半
// 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));
我有以下代码,它制作了一个基本的窗格,里面有一个矩形:
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);
}
我已经尝试了一些方法来使三角形的中心位于窗格的中心(上面代码中的一个示例),但是因为在 JavaFX 中,矩形的 X 和 Y 坐标表示左上角它使它更难在我的窗格中居中。我的数学很差,不知道实现此目标的正确公式。 如何让矩形的中心与窗格的中心对齐? 不使用 Stackpane 等...
您想将矩形的中点与窗格的中点对齐。
您必须找到窗格(x 和 y)和矩形(x 和 y)的中点。
// Find the midpoint of the Pane.
// x midpoint
float xPaneMidpoint = pane.width / 2
// y midpoint
float yPaneMidpoint = pane.height/ 2
然后将矩形移动到窗格的中点位置,然后将其偏移其大小的一半
// 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));