Center stage on parent stage

前端 未结 2 1870

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

2条回答
  •  春和景丽
    2020-12-03 14:48

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

提交回复
热议问题