Center stage on parent stage
Asked Answered
E

2

19

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?

private void show(Stage parentStage) {
    mystage.initOwner(parentStage);
    mystage.initModality(Modality.WINDOW_MODAL);
    mystage.centerOnScreen();
    mystage.initStyle(StageStyle.UTILITY);
    mystage.show();
 }
Electrolyse answered 4/12, 2012 at 11:47 Comment(0)
H
22

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);
    }
}
Hower answered 4/12, 2012 at 12:13 Comment(2)
If you don't explicitly set the width and height of the childStage, then you can perform the calculation in an event handler for the childStage.setOnShown event.Bombard
For how hinky this may seem, the child stage gets its sizes at construction when I do this... childStage.toBack(); childStage.show(); childStage.hide(); childStage.toFront();Terceira
D
1

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();
Diacritic answered 20/3, 2016 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.