How can I access a Controller class in JavaFx 2.0?
Asked Answered
B

4

15

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!

Bowse answered 20/4, 2012 at 4:54 Comment(2)
Maybe this answer could be helpful: https://mcmap.net/q/261347/-javafx-2-0-fxml-updating-scene-values-from-a-different-task.Ectophyte
possible duplicate of JavaFX 2.0 + FXML. Updating scene values from a different TaskForan
S
49

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

Subdual answered 20/4, 2012 at 7:44 Comment(2)
Thank you very much!Your method is quite what I need!Thank you angain!Bowse
I have a situation where fxmlLoader.getController() didn't work that way. But I don't know why!Frohman
D
5

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.

Diorio answered 7/1, 2014 at 6:34 Comment(0)
F
0

Use getResourceAsStream instead :

anchorPane = loader.load(LightView.class.getResourceAsStream(fxmlFile));

Its simple, work well.

Foresheet answered 2/1, 2015 at 1:57 Comment(0)
C
0

You can try this...

    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("LightView.fxml"));
    loader.load();
    Parent parent = loader.getRoot();
    Scene Scene = new Scene(parent);
    Stage Stage = new Stage();
    LightViewController lv = loader.getController();
    lv.setLight(light);
    Stage.setScene(Scene);
    Stage.show();
Crackpot answered 12/3, 2017 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.