Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does FXMLLoader load the FXML's controller?

What happens when I call FXMLLoader#load() in JavaFX?

Suppose the FXML controller extends a class that has a constructor. Will there be assurance that the constructor will be called? And if not, how will a new instance of the object be created? For example, in the code below, will the TextField() constructor be called?

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
public class FXMLController extends TextField implements Initializable {
    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }    
}

I already tried searching this one out but there seems to be no documentation about it aside from "Loads an object hierarchy from a FXML document." from http://docs.oracle.com/javafx/2/api/javafx/fxml/FXMLLoader.html

Your answers will be appreciated. Thanks a lot!

like image 718
damat-perdigannat Avatar asked Oct 09 '13 07:10

damat-perdigannat


2 Answers

To answer your question "what does a FXMLLoader do exactly when building a controller?":

first it will try to get a controller instance:

  • if there is already a controller instance set on the FXMLLoader, it will use this instance.
  • if there is no controller factory set on the FXMLLoader, it tries to call a zero-argument-constructor of the class per reflection. If this fails, an InstantiationException is thrown.
  • if there is a controller factory set, it will call this factory to create a new controller instance.

after getting the controller instance, it will do the following with it:

  • if this class implements Initializable, it calls public void initialize(URL url, ResourceBundle resourceBundle). If not, it looks if there is a method called initialize with zero arguments and calls it via reflection. If not, it does nothing.
like image 145
zhujik Avatar answered Oct 14 '22 16:10

zhujik


I'm not entirely sure what you are trying to do but normally the controller should not extend a textfield.

That aside, this is basic java stuff: textfield has an empty constructor, your controller has none so java will (by default) call the empty constructor available in TextField. The TextField constructor will by default (even if it's not in the code) call the constructor of the class it extends and so on. There is no way to construct an object in java without a constructor being called.

like image 36
nablex Avatar answered Oct 14 '22 15:10

nablex