JavaFX(ML)中可以使用单例控制器吗? [英] Is a singleton controller possible in JavaFX(ML)?

查看:103
本文介绍了JavaFX(ML)中可以使用单例控制器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用单例模式实现一个控制器,就像在网络上描述过几次.

I tried to implement a controller with the singleton pattern like described a couple of times on the web.

但是由于以下异常,我无法使应用程序运行.

However I cant get the application to run because of the following exception.

java.lang.IllegalAccessException: Class sun.reflect.misc.ReflectUtil can not access a member of class testapp.Controller with modifiers "private"

我猜那是因为构造函数被声明为私有.我现在看不到我在做什么错.

I guess thats because the constructor is declared private. I dont see what I am doing wrong at this point.

如果我不清楚我的问题是什么,我将描述我将要做的用例.

In case I wasn't clear what my problem is I will describe the use case of what I am going to do.

start(Stage stage)函数中,afaik是可以定义onclose事件的唯一位置(如果我错了,请纠正我).在关闭窗口时,需要执行一些清理操作.这些操作在控制器内部,我无法在start() function中进行访问.因此,我们的想法是将控制器构建为单例,以保持单个实例存活并为主要类提供访问权限.

Inside the start(Stage stage) function afaik is the only place the onclose event can be defined(please correct me if I am wrong). On closing the window some clean-up operations need to be exectued. These operation are inside the controller which I cant get access of in the start() function. Therefore the idea was to build the controller as a singleton to keep one single instance alive and provide acces to the main class.

链接在JavaFX中创建Singleton Controller类建议对我来说,sillyfly似乎不是一个可能的解决方案,因为控制器被传递给了模型类而不是主类.此外,模型构造函数是手动调用的,这不是我要处理的情况.

The Link Creating a Singleton Controller class in JavaFX advised by sillyfly seems not to be a possible sollution for me bacause the controller is passed to a model class not the main class. Also the model constructor is called manually which is not the case I am dealing with.

推荐答案

要解决您的问题,您有两种可能.您可以将自己的实例控制器提供给实例化的FXML加载器 https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#setController-java.lang.Object- 或者为FXML加载器提供控制器工厂,该工厂知道如何实例化控制器. https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#setControllerFactory-javafx.util.Callback-

To solve your problem you have two possibilities. Either you provide an instance of your singleton controller to the FXML loader which you have instantiated yourself https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#setController-java.lang.Object- or you provide the FXML loader with a controller factory which knows how to instantiate your controller. https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#setControllerFactory-javafx.util.Callback-

这篇关于JavaFX(ML)中可以使用单例控制器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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