10

When working with JavaFX Scene Builder encountered the following problem...

Given:

A file fxml, containing description Anchor Pane (fxml formed from Scene Builder);
For Anchor Pane is not specified Controller Class.
This fxml loaded into the Java Application by using FXMLLoader.

Need:

After downloading the Anchor Pane set the value to Controller Class.
It is necessary for to load the same fxml with different handlers.

Question: is it possible, and if so - how to implement?

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
Rams
  • 103
  • 1
  • 1
  • 5

1 Answers1

20

The controller class of the loading FXML file can also be set through the Scene Builder. But you want to set it at loading time in the application. To achieve that you should set the controller of the FXMLLoader before the load() method is called:

AnchorPane rootPane;
MyController controller = new MyController();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("my.fxml"));
fxmlLoader.setRoot(rootPane);
fxmlLoader.setController(controller);
fxmlLoader.load();
Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
  • Uluk Biy, hi, I tried your answer and worked for me. I got a question, How can I set the controller class with the designer ? I don't know what to put in the "Controller class" field, I tried with just the name of the controller class, package/name, appname/package/name ... If you know or can give me an example... thank you – Mauricio Sep 05 '15 at 13:15
  • @HoNgOuRu unfortunately I haven't used the scene builder. – Uluk Biy Sep 07 '15 at 04:37
  • 1
    hi, thanks for answering. The problem was that the scene builder was removing the import statement of the package from the fxml before saving it. – Mauricio Sep 07 '15 at 06:05