加载到FXML中时,start方法中控制器类的JavaFx可选参数 [英] JavaFx optional parameters for controller class in start method when it is loaded into the FXML

查看:91
本文介绍了加载到FXML中时,start方法中控制器类的JavaFx可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ScheneBuilder定义了fxml的控制器类,在AnchorPane标记内生成的代码是:

with the ScheneBuilder I defined the controller class of my fxml, the code genereted inside my AnchorPane tag is:

fx:controller="demo.SplashController"

现在,我想在主目录中使用args,以使用适当的结构加载控制器的新版本.我在Application.start中尝试以下代码:

now I would like if I had args in the main, to load a new version of the controller, using the appropriate construct. I try this code in the Application.start:

FXMLLoader loader = new FXMLLoader(getClass().getResource("page.fxml"));
PageController controller;
if(!dir.equals("")){ //attribute coming from args
  controller = new PageController(dir);
}else{
  controller = new PageController();  
}
loader.setController(controller);
AnchorPane root = loader.load();
Scene scene = new Scene(root,480,414);
primaryStage.setScene(scene);
primaryStage.show();

但是使用此代码会出现冲突,因为我已经在我的项目中使用FXML代码定义了控制器,要解决该问题,就可以删除FXML代码中的段,但是我不会这样做,因为将代码保留在fxml允许我访问SceneBuilder的一些良好功能.

but using this code a conflict appears because I have already defined the controller in my project with FXML code, to solve it would be enough to remove the segment in the FXML code but I would not do it because leaving the code in the fxml allows me to access some good features of the SceneBuilder.

推荐答案

将参数传递给控制器​​的构造函数的唯一方法是在fxml中指定控制器的类是使用控制器工厂:

The only way pass parameters to the controller's constructor and specify the controller's class in the fxml is to use a controller factory:

FXMLLoader loader = new FXMLLoader(getClass().getResource("page.fxml"));
loader.setControllerFactory(cl -> dir.isEmpty() ? new PageController() : new PageController(dir));
AnchorPane root = loader.load();


另一种选择是在控制器类中创建一个方法,该方法允许您在加载后传递信息并进行初始化:


Another option would be to create a method in the controller class that allows you to pass the info after loading and does the initialisation:

FXMLLoader loader = new FXMLLoader(getClass().getResource("page.fxml"));
AnchorPane root = loader.load();
PageController controller = loader.getController();
controller.setDir(dir);

请注意,假设有一个方法调用,在initialize方法运行之后发生.

Note that the method call happens after the initialize method is run assuming there is one.

这篇关于加载到FXML中时,start方法中控制器类的JavaFx可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆