我想在其父窗口的中心上方打开一个对话框窗口,因此我使用以下公式:
Window window = ((Node) actionEvent.getSource()).getScene().getWindow();
Scene scene = new Scene(new Group(new DialogWindow()));
Stage dialog = new Stage();
dialog.initOwner(window);
dialog.sizeToScene();
dialog.setX(stage.getX() + stage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = NaN
dialog.setY(stage.getY() + stage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = NaN
dialog.setScene(scene);
dialog.show(); //it is better to showAndWait();我没有手动设置大小,因为我需要自动调整窗口大小以适应其内容的大小。
在Linux下,它将窗口直接设置在父窗口的中心。但在Windows中它不起作用,并导致不同的结果。
如果不手动设置对话框的宽度和高度,如何获取它们?
发布于 2013-09-28 19:30:10
Stage的宽度和高度是在显示后计算的(.show())。在此之后进行计算:
...
dialog.show();
dialog.setX(stage.getX() + stage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = not NaN
dialog.setY(stage.getY() + stage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = not NaN编辑:
如果使用showAndWait()而不是show(),则由于showAndWait()会阻塞调用者事件,因此showAndWait()之后的计算也会被阻塞。解决方法之一可能是在新的Runnable中之前进行计算
final Stage dialog = new Stage();
dialog.initOwner(window);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.sizeToScene();
dialog.setScene(scene);
Platform.runLater(new Runnable() {
@Override
public void run() {
dialog.setX(primaryStage.getX() + primaryStage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = NaN
dialog.setY(primaryStage.getY() + primaryStage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = NaN
}
});
dialog.showAndWait();另请注意initModality。如果是showAndWait(),则必须设置模态。否则,使用showAndWait()是没有意义的。
发布于 2014-02-17 19:17:16
试试这个:
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
System.out.println(screenBounds.getHeight());
System.out.println(screenBounds.getWidth());https://stackoverflow.com/questions/19025935
复制相似问题