如何引用primaryStage

我使用.fxml-Files作为我的应用程序的视图层。 每个fxml都附有一个控制器

 

我们假设我有一个mainFrame和它的控制器。 mainFrame.fxml在start(Stage) -method中加载。

现在你要显示一个附加到Stage / Window / Whatever的fileChooser。

为此,让fxml-controller知道例如 primaryStage

有没有办法将它注入控制器,或者FXML在运行时是否知道它属于哪个场景和阶段?

我只有想法是将primaryStage存储在一些静态上下文中,但这似乎不是一种对我这样做的方法。

不是FXML,而是FXML(或其控制器)中的节点(控件)知道它们在运行时属于哪个场景和阶段(在添加到场景之后)。
在控制器类中,

 ... @FXML private Label label; ... // in some method block Stage stageTheLabelBelongs = (Stage) label.getScene().getWindow(); 

或者,您可以使用CDI事件来获得主要阶段。 查看由CDI和JBoss Weld提供支持的博客文章FXML和JavaFX 。

强大的解决方案(可用作片段):接受一个事件,然后获得触发该事件的控制权。 使用该控件获取舞台:

 @FXML private void browseDirectory(ActionEvent event) { Stage stage = Stage.class.cast(Control.class.cast(event.getSource()).getScene().getWindow()); DirectoryChooser directoryChooser = new DirectoryChooser(); File selectedDirectory = directoryChooser.showDialog(stage); System.out.println(selectedDirectory.getAbsolutePath()); } 

http://code.makery.ch/java/javafx-2-tutorial-part5

这是一个使用示例代码示例执行此操作的好教程

  Controller... //Application class type variable public MainApp mainApp; public Stage stage; ......... ......... /** * Is called by the main application to give a reference back to itself. * * @param mainApp */ public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; } } ..... ......... @FXML public void initialize(){ stage=mainApp.getStage(); } Application class.... class MainApp extends Application{ Stage stage; ... ... @Override public void start(Stage stage) { this.stage=stage; FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("view/PersonOverview.fxml")); PersonOverviewController controller = loader.getController(); controller.setMainApp(this); } ... ,, public getStage() { return this.stage; } }