我将.fxml-Files用于我的应用程序的视图层。每个fxml都附有一个控制器
<AnchorPane fx:controller="movielistjavafx.view.MainWindowController">
假设我有一个mainFrame和它的控制器。 mainFrame.fxml加载在start(Stage)
- 方法。
现在您要显示一个附加到舞台/窗口/随便的fileChooser。
为此,让fxml-controller了解例如 primaryStage
会很好。
有没有办法将它注入控制器,或者FXML在运行时是否知道它属于哪个场景和阶段?
我只有想法是将primaryStage存储在某些静态上下文中,但这似乎不是一种对我这样做的方法。
答案 0 :(得分:30)
不是FXML,但FXML(或其控制器)中的节点(控件)知道它们在运行时属于哪个场景和阶段(在添加到场景之后)。
在控制器类中,
...
@FXML private Label label;
...
// in some method block
Stage stageTheLabelBelongs = (Stage) label.getScene().getWindow();
或者,您可以使用CDI事件来获得主要阶段。查看博客条目FXML & JavaFX powered by CDI & JBoss Weld。
答案 1 :(得分:7)
强大的解决方案(可用作代码段):接受一个事件,然后获得触发该事件的控制权。使用该控件获取舞台:
@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());
}
答案 2 :(得分:4)
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;
}
}