gpt4 book ai didi

javafx - 在 Controller 内加载 FXML 文件,但也使用 NetBeans 的 "Make Controller"

转载 作者:行者123 更新时间:2023-12-02 01:40:50 24 4
gpt4 key购买 nike

在尝试加载 FXML 文件时,通常会执行以下操作:

FXMLLoader loader = FXMLLoader.load(getClass().getResource("File.fxml"));
Region root = loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();

但是,当我尝试将加载代码放入 Controller 中以方便“调用者”时,我执行了以下操作:

public Controller()
{
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxml));
loader.setController(this);
Parent root = loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
}

这非常有效,因为现在我只需调用构造函数来创建新窗口。

但我必须删除

fx:controller="package.Class"

FXML 文件中的属性,因为否则当我调用时会抛出异常(“javafx.fxml.LoadException: Controller 已设置”)

fxmlloader.setController(this);

构造函数中的方法。由于我使用 NetBeans 及其“创建 Controller ”功能(右键单击 FXML 文件),因此由于缺少属性而无法创建 Controller 类。

摘要:

我想要实现的是一种在 FXML(对于 NetBeans)中仍然设置“fx:controller”属性的方法,并且还能够在 Controller 类中方便地加载 FXML。

这可能吗,还是我需要某种包装类来创建 FXML 窗口?

提前致谢。

最佳答案

你可以这样做:

public Controller()
{
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxml));
loader.setControllerFactory(type -> {
if (type == Controller.class) {
return this ;
} else {
try {
return type.newInstance();
} catch (RuntimeException e) {
throw e ;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
Parent root = loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
}

这将允许您(事实上,您需要)在 FXML 文件中拥有 fx:controller 属性。基本上,它的作用是指定一个函数,FXMLLoader 可以使用该函数从指定的类获取 Controller 实例。在这种情况下,如果 FXML 加载器正在查找 Controller 类的对象,它将返回当前对象,否则仅创建指定类的新对象。

关于javafx - 在 Controller 内加载 FXML 文件,但也使用 NetBeans 的 "Make Controller",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44487811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com