gpt4 book ai didi

javafx加载FXML文件的实用方法

转载 作者:行者123 更新时间:2023-11-30 07:02:34 25 4
gpt4 key购买 nike

我有几个实例想要加载相同的 FXML 文件以捕获一些信息。

理想情况下,这将是开发实用方法的情况,即编写一次,使用多次。

这是一个当前示例,在类中使用私有(private)方法:

private ServiceEvent_NewController loadServiceEvent_Stage(Stage primaryStage)
{
ServiceEvent_NewController controller = null;

try
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/View/ServiceEvent_New.fxml") );
Parent root = loader.load();

// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(root);
dialogStage.setScene(scene);

controller = loader.getController();
controller.setDialogStage(dialogStage);

}
catch (IOException npe)
{
String message = npe.getMessage();
System.out.println(message);
}

return controller;
}

我有一个实用程序类(public final class LM_Utility)。
如果我尝试创建一个方法来加载 FXML,使用:

public static ServiceEvent_NewController loadServiceEvent_Stage(Stage primaryStage) 

编译器提示“无法从静态上下文引用非静态方法 getClass()”

是否有某种方法可以创建合适的实用方法来加载此类文件,以便我可以“编写一次并使用多次”?

最佳答案

getClass()返回该方法包含的运行时类。

如果您不需要使用相对于扩展类的位置的效果,您可以简单地替换

getClass()

LM_Utility.class

这是 Class 的表达式LM_Utility 的对象类,这是什么getClass()将以非静态方法返回,因为 LM_Utilityfinal .

当然,您可能应该将 fxml 文件的资源路径传递给该方法,并使用包含 setDialogStage 的接口(interface)或抽象类。而不是硬编码对象类型。您可以使用类型参数 <T extends ControllerInterface>允许您使用实际 Controller 类型作为分配的目标。 (但请注意,在运行时此分配仍将有效地包含对目标类型的强制转换。)

关于javafx加载FXML文件的实用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649607/

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