FXMLLoader如何加载FXML的控制器? [英] How does FXMLLoader load the FXML's controller?
问题描述
当我在JavaFX中调用FXMLLoader#load()时会发生什么?
What happens when I call FXMLLoader#load() in JavaFX?
假设FXML控制器扩展了一个具有构造函数的类。是否可以保证将调用构造函数?如果没有,将如何创建对象的新实例?例如,在下面的代码中,是否会调用TextField()构造函数?
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) {
}
}
我已经尝试过搜索这个了但是除了加载对象层次结构之外似乎没有关于它的文档一份FXML文件。来自 http://docs.oracle.com/javafx/2/ api / javafx / fxml / FXMLLoader.html
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!
推荐答案
回答你的问题构建控制器时FXMLLoader完全做了什么?:
To answer your question "what does a FXMLLoader do exactly when building a controller?":
首先它会尝试获取控制器实例:
first it will try to get a controller instance:
- 如果已有控制器在FXMLLoader上设置实例,它将使用此实例。
- 如果FXMLLoader上没有设置控制器工厂,它会尝试按反射调用类的零参数构造函数。如果失败,则抛出InstantiationException。
- 如果设置了控制器工厂,它将调用此工厂来创建新的控制器实例。
获取控制器实例后,它将执行以下操作:
after getting the controller instance, it will do the following with it:
- if这个类实现了Initializable,它调用public void initialize(URL url,ResourceBundle resourceBundle)。如果没有,它会查看是否存在一个名为initialize且零参数的方法,并通过反射调用它。如果没有,它什么都不做。
这篇关于FXMLLoader如何加载FXML的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!