在SceneBuilder中创建

在SceneBuilder中创建

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

问题描述

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



加载场景的fxml文件时,我的程序是否只加载该fxml文件的控制器文件的副本?


解决方案

您的控制器可以帮助您解决这个问题。 file是一个Java源文件,它被编译为单个Java类,从中可以创建许多Java对象实例。



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



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



类似地,如果加载所有由同一控制器类支持的不同fxml文件 - 每次你任何fxml文件,您将获得一个新的控制器实例。




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



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





此外,使用将允许您共享信息。只是不要结合使用静态 @FXML







  • 注意:技术上可以在多个FXML档案



    正如Greg Brown在评论中指出:

    我强烈不建议采用以下方法,相关答案中进一步解释:






    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.

    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.

    解决方案

    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.

    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.

    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.

    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.


    Update to answer additional question on Controller data sharing

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

    Passing Parameters JavaFX 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.

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


    Note: it is technically possible to share a single controller among multiple FXML files

    As pointed out in comments by Greg Brown:

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

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

    07-29 12:34