Center stage on parent stage

老子叫甜甜 提交于 2019-11-27 14:38:45

You can use the parent stage's X/Y/width/height properties to do that. Rather than using Stage#centerOnScreen, you could do the following:

public class CenterStage extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        stage.setX(300);
        stage.setWidth(800);
        stage.setHeight(400);
        stage.show();

        final Stage childStage = new Stage();
        childStage.setWidth(200);
        childStage.setHeight(200);
        childStage.setX(stage.getX() + stage.getWidth() / 2 - childStage.getWidth() / 2);
        childStage.setY(stage.getY() + stage.getHeight() / 2 - childStage.getHeight() / 2);
        childStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}
Burtan

When you don't determine a size for the childStage, you have to listen for width and height changes as width and height is still NaN when onShown is called.

final double midX = (parentStage.getX() + parentStage.getWidth()) / 2;
final double midY = (parentStage.getY() + parentStage.getHeight()) / 2;

xResized = false;
yResized = false;

newStage.widthProperty().addListener((observable, oldValue, newValue) -> {
    if (!xResized && newValue.intValue() > 1) {
        newStage.setX(midX - newValue.intValue() / 2);
        xResized = true;
    }
});

newStage.heightProperty().addListener((observable, oldValue, newValue) -> {
    if (!yResized && newValue.intValue() > 1) {
        newStage.setY(midY - newValue.intValue() / 2);
        yResized = true;
    }
});

newStage.show();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!