简体   繁体   English

父母舞台上的中心舞台

[英]Center stage on parent stage

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. 我正在JavaFx中创建一个应用程序,如果有任何子阶段被打开,我想要这样做,然后它应该在父阶段的中心打开。 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. 我试图使用mystage.centerOnScreen()来做这个,但它会将子阶段分配到屏幕的中心,而不是父阶段的中心。 How can I assign the child stage to center of parent stage? 如何将子阶段分配到父阶段的中心?

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

You can use the parent stage's X/Y/width/height properties to do that. 您可以使用父级的X / Y /宽度/高度属性来执行此操作。 Rather than using Stage#centerOnScreen , you could do the following: 您可以执行以下Stage#centerOnScreen ,而不是使用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);
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM