问题描述
我一直在尝试FXMLLoader
,并通过自定义Callback<P,R>
实现使用setControllerFactory
方法.
I have been experimenting with the FXMLLoader
and using the setControllerFactory
method using a custom Callback<P,R>
implementation.
ORACLE文档表示以下内容:
我想要实现的结果是,我可以使用依赖项注入框架来创建任何需要参数的控制器,但是我将让FXMLLoader
加载任何不需要参数的控制器.
The result I want to achieve is that I can use a dependency injection framework to create any controllers that require parameters but I will let the FXMLLoader
load any controllers that do not require parameters.
因此,如果我有以下简单的FXML文件,该文件使用ViewController
类,该类不接受任何参数...
So if I have the following simple FXML file which uses the ViewController
class which accepts no parameters...
<StackPane fx:id="pane"
xmlns:fx="http://javafx.com/fxml"
fx:controller="my.package.ViewController">
</StackPane>
,并且我使用以下简单的控制器工厂实现向FXMLLoader
发出信号,要求我在这种情况下管理控制器的构造...
and I use the following simple controller factory implementation to signal to the FXMLLoader
that I want it to manage the construction of the controller in this case...
loader.setControllerFactory(new Callback<Class<?>, Object>(){
@Override
public Object Call(Class<?> type) {
return null; // Let the FXMLLoader handle construction...
}
});
调用load()
方法后,再也不会调用ViewController
类中的Initialize方法(我已经用断点验证了这一点).
after calling the load()
method my Initialise method in the ViewController
class is never called (I have verified this with a breakpoint).
如果我更改控制器工厂的实现以返回ViewController
类的实例,那么一切都会按预期进行.
If I change my controller factory implementation to return an instance of the ViewController
class then everything works as expected.
有人可以帮助我消除混乱吗?我是错误地使用Callback
界面还是ORACLE文档不正确?
Can anyone help me to clear up my confusion? Am I using the Callback
interface incorrectly or is the ORACLE documentation incorrect?
推荐答案
javafx在FXMLLoader中执行以下操作:
javafx does the following in FXMLLoader:
try {
if (controllerFactory == null) {
setController(ReflectUtil.newInstance(type));
} else {
setController(controllerFactory.call(type));
}
} catch (InstantiationException exception) {
throw new LoadException(exception);
} catch (IllegalAccessException exception) {
throw new LoadException(exception);
}
所以,是的,oracle教程不正确.
so, yes, the oracle tutorial is incorrect.
这篇关于JavaFX自定义控制器工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!