Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a Controller class in JavaFx 2.0?

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

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

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

3.LightViewController.java

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

4.Light.java

.... a simple pojo

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!

like image 984
yinger090807 Avatar asked Apr 20 '12 04:04

yinger090807


2 Answers

I use the following :

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

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

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

In this way fxmlLoader.getController() is not null

like image 74
Alf Avatar answered Nov 18 '22 19:11

Alf


In addition to Alf's answer, I want to note, that the code can be shorter:

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

FXMLLoader fxmlLoader = new FXMLLoader();

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

This works as well.

like image 36
ITurchenko Avatar answered Nov 18 '22 19:11

ITurchenko