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

查看:43
本文介绍了如何访问 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 对象(它们来自一个列表).有谁能帮帮我吗?非常感谢!

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天全站免登陆