JavaFX 多个 FXML 和 1 个共享控制器 [英] JavaFX multiple FXML and 1 shared controller

查看:20
本文介绍了JavaFX 多个 FXML 和 1 个共享控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个根 FXML,它是一个 BorderPane,它有自己的根控制器.我想动态地将 FXML 添加到此边框的中心.

I have created a root FXML which is a BorderPane and it has his own root controller. I want to dynamicly add FXML's to the center of this borderpane.

这些 fxml 中的每一个都共享相同的控制器,即根控制器.我在 netbeans 中通过在创建空的 FXML 文件时选择一个现有的控制器来做到这一点.

Each of these fxml's share the same controller, root controller. I have done this in netbeans by choosing an exsisting controller when creating an empty FXML file.

我还为节点指定了不同的 id 名称,但根控制器无法识别这些 fxml 中的节点.

I also have gave the nodes different id names, but the root controller does not recognize the nodes in these fxml's.

是否可以为不同的 fxml 共享同一个控制器?

Is it possible to share the same controller for different fxml's?

提前致谢

推荐答案

背景

我不知道真的推荐共享控制器实例,至少我以前从未见过这样做过.

I don't know that sharing a controller instance is really recommended, at least I've never seen it done before.

即使您将要加载的每个 fxml 中的控制器类设置为相同的值,它也不会共享相同的控制器实例,因为每次加载控制器时,它都会创建一个新实例(对象)的控制器类(这似乎不是你想要的).

Even if you set the controller class in each of the fxml's you are loading to the same value, it isn't going to share the same controller instance, because every time you load a controller, it will create a new instance (object) of the controller class (which doesn't seem to be what you want).

潜在解决方案

我还没有尝试过这两种解决方案,但相信它们会奏效.

I haven't tried either of these solutions, but believe they will work.

可能会在每次加载新的 fxml 文件时调用 initialize 方法.因此,您需要通过使 initialize idempotent 在您的逻辑中考虑到这一点.

The initialize method will probably be called each time you load a new fxml file. So you will want to account for that in your logic by making initialize idempotent.

A.手动设置控制器实例.

  1. 从 fxml 文件中删除对控制器类的所有引用.
  2. 手动创建控制器类的实例.

  1. Remove all of the references to your controller class from your fxml files.
  2. Manually create an instance of your controller class.

MyController controller = new MyController(); 

  • 在加载每个 fxml 之前将控制器设置为您的控制器实例.

  • Set the controller to your controller instance before you load each fxml.

    FXMLLoader loader = new FXMLLoader();
    loader.setController(controller);
    Panel panel = (Panel) loader.load("myfxml.fxml");
    

  • 对每个 fxml 文件重复步骤 3,每次使用相同的控制器引用.

  • Repeat step 3 for each of your fxml files, using the same controller reference each time.

    B.使用控制器工厂.

    您可以在 fxml 加载器上设置控制器工厂,并让控制器工厂始终返回相同的控制器实例.

    You can set a controller factory on your fxml loaders and have the controller factory always return the same controller instance.

    这篇关于JavaFX 多个 FXML 和 1 个共享控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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