FXMLLoader无法找到正在运行的控制器实例并创建新的实例 [英] FXMLLoader cannot find running controller instance and creates new one

查看:254
本文介绍了FXMLLoader无法找到正在运行的控制器实例并创建新的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于JavaFX,我是新手,我最近遇到了一个让我很困惑的问题。我正在使用一个名为MainController的类来控制包含TabPane的FXML文件。每个选项卡由另一个控制器控制。但是有一种情况需要删除选项卡,因此我需要访问MainController实例以从窗格中删除当前活动的选项卡。

I'm a newcomer when it comes to JavaFX and I recently encountered a problem which really confuses me alot. I'm using a class called "MainController" which controlls an FXML-File containing a TabPane. Each tab is controlled by another controller. But there is one situation in which a tab needs to be deleted, so I need access to the MainController instance to remove the currently active tab from the pane.

每当我'使用此代码获取当前运行的MainController的实例,我得到一个全新的实例,其所有组件都设置为默认值。

Whenever I'm using this code to get an instance of the currently running MainController, I instead get a completely new instance with all of its components set to their default values.

代码是:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
loader.load();
MainController controller = loader.getController();
controller.closeCurrentTab();

protected void closeCurrentTab() {
    tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedIndex());
}

我正在使用对控制器的静态引用来访问它,因为它是唯一适合我的解决方案。但我知道这是非常不专业的,我真的想避免这种情况。

I'm currently using a static reference to the controller to access it since it is the only solution that works for me. But I know that this is highly unprofessional and I really want to avoid that.

我希望有人知道这里有什么问题。

I hope somebody knows what's wrong here.

推荐答案

您应该确保在您想要使用它的地方有一个主控制器的参考。我猜它是子控制器之一(很可能是当前标签的控制器)。

You should ensure that you have a reference for your main controller at the point where you want to use it. I guess it is one of the "child" controllers (most probably the controller of the current tab).

因此,如果你在这个类中有一个属性来存储你的主控制器的参考,你的问题将得到解决。

Therefore if you would have a property in this class that stores the reference for your main controller, your problem would be solved.

我猜你从主控制器初始化这个子控制器,如:

I guess you initialize this "child" controller from the main controller like:

FXMLLoader loader = new FXMLLoader(getClass().getResource("TabController1.fxml"));
loader.load();

所以你可以这样做:

TabController controller = loader.getController();
controller.mainControllerProperty.set(this);

其中 mainControllerProperty 在<$ c中定义$ c> TabController 喜欢:

ObjectProperty<MainController> mainControllerProperty = new SimpleObjectProperty();

这篇关于FXMLLoader无法找到正在运行的控制器实例并创建新的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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