JavaFX自定义控制器工厂 [英] JavaFX custom controller factory

查看:89
本文介绍了JavaFX自定义控制器工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试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文档表示以下内容:

一个实现可能返回一个空值来表示它确实 没有或不能创建给定类型的控制器;在这种情况下, 默认的控制器构造机制将由 加载器.

An implementation might return a null value to indicate that it does not or cannot create a controller of the given type; in this case, the default controller construction mechanism will be employed by the loader.

我想要实现的结果是,我可以使用依赖项注入框架来创建任何需要参数的控制器,但是我将让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自定义控制器工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆