1

I have some doubts regarding accessing javafx controller class. I have seen that all of the time we use getController() method of FXMLLoader class to access a controller class. Why don't we use constructor invocation using new operator and accessing it. i.e. like

 TestController mc =  new TestController();
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
Angom
  • 721
  • 1
  • 11
  • 27
  • What do you want a reference to? Do you want a reference to a new controller, or do you want a reference to the controller the FXMLLoader created and initialized? `new TestController()` gives you the first, `loader.getController()` gives you the second. – James_D Feb 18 '14 at 12:40
  • I want controller with initialised. I asked this because I just wanted to know whether using constructor invocation also can do the same thing as using getController(). It seems working as mentioned in the Uluk's answer. – Angom Feb 18 '14 at 12:53

1 Answers1

3

A few things that come to mind regarding to usage of constructor invocation. You should load the FXML file yourself, parse it and construct the node graph defined in it, then, do the following steps :

  • the @FXML annotated fields must be bound between node graph and controller class
  • the eventHandlers in controller must be attached to the right nodes where defined in FXML
  • calling the constructor's initialize() method in right place in right time
  • and much more staff that FXMLLoader do while it is load()ing ...

Those staffs can be explored in FXMLLoader's source code.
Having said that, you can still invoke constructor yourself but set it to FXMLLoader before calling FXMLLoader's load methods as:

TestController mc = new TestController();
FXMLLoader loader = new FXMLLoader();
loader.setController(mc);
loader.load();

This way all above mentioned "dirty works" will be handled by FXMLLoader, then "Don't worry, be happy" :).

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153