有多个 FXML 文件(在 SceneBuilder 中创建),但只有一个控制器.每个场景是否加载它自己的控制器副本? [英] Have multiple FXML files (created in SceneBuilder), but only one controller. Does each scene load it's own copy of the controller?

查看:14
本文介绍了有多个 FXML 文件(在 SceneBuilder 中创建),但只有一个控制器.每个场景是否加载它自己的控制器副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 SceneBuilder 中创建了多个 FXML 文件和一个控制器文件.当我在一个场景中编辑一个值(例如,一个整数值),然后切换场景时,该值在新场景中似乎没有改变.

I have multiple FXML files I have created in SceneBuilder and one controller file. When I edit a value (say for instance, an integer value) in one scene, and then switch scenes, that value does not seem to have been changed in the new scene.

当加载场景的 fxml 文件时,我的程序是否加载了控制器文件的副本,仅用于(并且仅供)该 fxml 文件?

When loading the fxml file for a scene, is my program loading a copy of the controller file just for (and used only by) that fxml file?

非常感谢你们能提供的任何帮助来回答这个问题.

Really appreciate any help you guys can give answering this question.

推荐答案

您的控制器文件是一个 Java 源文件,它被编译为单个 Java 类,从中可以创建许多 Java 对象实例.

Your controller file is a Java source file which gets compiled to a single Java class from which many Java object instances may be created.

在运行时,默认的 fxml 加载器控制器工厂实现将创建一个新的控制器实例(即一个新对象),每次调用 fxml 加载器的 加载方法.

At runtime the default fxml loader controller factory implementation will create a new controller instance (i.e. a new object), every time you invoke the fxml loader's load method.

即使你一遍又一遍地加载同一个 fxml 文件,加载器每次都会创建一个新的控制器实例,每个实例都有自己的内部状态,独立于所有其他的.

Even if you are loading the same fxml file over and over again, the loader will create a new controller instance each time, each with it's own internal state independent of all others.

同样,如果你加载不同的 fxml 文件,所有这些文件都由同一个控制器类支持 - 每次你加载任何 fxml 文件时,你都会得到一个新的控制器实例.

Similarly, if you load different fxml files all backed by the same controller class - each time you any fxml file, you will get a new controller instance.

更新以回答有关控制器数据共享的其他问题

要使用依赖注入或单独的初始化方法在控制器之间共享信息,请参阅:

To share information between controllers using dependency injection or a separate initialization method, see:

传递参数 JavaFX FXML

此外,使用静态类成员将允许你分享信息.只是不要将静态与 @FXML因为那行不通.

Also, use of static class members will allow you to share information. Just don't use static in combination with @FXML, as that won't work.

有一个很好的教程来处理多个 fxml 文件,您可能会发现它很有帮助:

There is a nice tutorial for working with multiple fxml files, which you may find helpful:

注意:技术上可以在多个 FXML 文件之间共享一个控制器

正如 Greg Brown 在评论中指出的那样:

As pointed out in comments by Greg Brown:

可以使用 FXMLLoader#setController()FXMLLoader#setControllerFactory() 更好地控制控制器实例化.

it is possible to exercise greater control over controller instantiation using FXMLLoader#setController() and FXMLLoader#setControllerFactory().

我强烈不推荐以下方法,相关回答中有进一步说明:

I strongly do not recommend the following approach, which is further explained in the related answer to:

这篇关于有多个 FXML 文件(在 SceneBuilder 中创建),但只有一个控制器.每个场景是否加载它自己的控制器副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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