如何在JavaFx 2.0中访问Controller类? [英] How can I access a Controller class in JavaFx 2.0?

查看:943
本文介绍了如何在JavaFx 2.0中访问Controller类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我用JavaFx2.0编写一个软件,但我遇到了一个大问题,那就是 - 我如何访问Controller类?
对于具有相同类类型的每个控制器类,它们可能因为它依赖的模型而有所不同,因此我想获取
视图的Controller类并为其提供指定的模型,我可以这个?
我试图通过FXMLLoader获取控制器,但方法getController()返回null!为什么?

Recently I was programming a software with JavaFx2.0,but I met with a big problem,that is - How can I access a Controller class? For every controller class with the same class type,they may act different because of the model it depends on,so I want to get the view's Controller class and provide it with the specified model,can I do this? I have tried to get the controller by the FXMLLoader,but the method getController() returns null!why?

1.LightView.java

1.LightView.java

FXMLLoader loader = new FXMLLoader();
anchorPane = loader.load(LightView.class.getResource(fxmlFile));//fxmlFile = "LightView.fxml"
//controller = (LightViewController) loader.getController();//fail to get controller!it is null
//I want to -> controller.setLight(light);

2.LightView.fxml

2.LightView.fxml

<AnchorPane ... fx:controller="light.LightViewController" >

3.LightViewController.java

3.LightViewController.java

....
private Light light;
public void initialize(URL arg0, ResourceBundle arg1)

4.Light.java



4.Light.java

.... a simple pojo

所以,我想做的是为每个LightViewController提供一个指定的Light Object(它们来自List)。

so,what I want to do is provide every LightViewController with a specified Light Object(they are from a List). Can anyone helps me?Thanks a lot!

推荐答案

我使用以下命令:

URL location = getClass().getResource("MyController.fxml");

FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());

Parent root = (Parent) fxmlLoader.load(location.openStream());

以这种方式 fxmlLoader.getController()不是 null

这篇关于如何在JavaFx 2.0中访问Controller类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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