2013-09-26 41 views
4

我想開上面它的父窗口的中心的對話窗口,所以我用下面的公式:JavaFX-2:如果沒有手動設置窗口大小,如何獲取窗口大小?

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中,它不起作用並導致不同的結果。

如果我沒有手動設置它們,我如何獲得對話框的寬度和高度?

回答

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()後的計算也被阻止。也

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:解決方法的一種方式可以在新Runnable之前做計算。模式必須在showAndWait()的情況下設置。否則使用showAndWait()是沒有意義的。

+0

它的工作原理。但只有'show()'。對於'showAndWait()',如果移動了主窗口,則會出現問題。如果我把它放在一邊,對話框仍然會出現在屏幕的中心。無論如何感謝這樣的解決方案,我會繼續尋求'showAndWait()':) – Dragon

+0

@Dragon的解決方案,請參閱更新。 –

+0

非常感謝。它真的很棒。 – Dragon

0

試試這個:

Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); 
<br> System.out.println(screenBounds.getHeight()); 
<br> System.out.println(screenBounds.getWidth());