java 父母舞台的中心舞台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13702191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:42:20  来源:igfitidea点击:

Center stage on parent stage

javajavafx-2javafxstage

提问by Ronak

I am creating an application in JavaFx, In which I want to do that if any child stage is getting opened then it should be opened in center of parent stage. I am trying to do this using mystage.centerOnScreen()but it'll assign the child stage to center of screen, not the center of parent stage. How can I assign the child stage to center of parent stage?

我正在 JavaFx 中创建一个应用程序,如果任何子阶段被打开,我想这样做,那么它应该在父阶段的中心打开。我正在尝试使用mystage.centerOnScreen()但它会将子舞台分配到屏幕中心,而不是父舞台的中心。如何将子舞台分配到父舞台的中心?

private void show(Stage parentStage) {
    mystage.initOwner(parentStage);
    mystage.initModality(Modality.WINDOW_MODAL);
    mystage.centerOnScreen();
    mystage.initStyle(StageStyle.UTILITY);
    mystage.show();
 }

回答by sarcan

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:

您可以使用父舞台的 X/Y/宽度/高度属性来做到这一点。Stage#centerOnScreen您可以执行以下操作,而不是使用:

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

回答by 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.

当您没有确定 childStage 的大小时,您必须监听宽度和高度的变化,因为在调用 onShown 时宽度和高度仍然是 NaN。

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