gpt4 book ai didi

切换场景的 JavaFX 问题

转载 作者:行者123 更新时间:2023-11-29 08:40:20 27 4
gpt4 key购买 nike

我有一个 Utility 类,我试图在其中创建一个名为 switchScenestatic 方法,以便能够轻松切换我的场景阶段。这是我尝试使用的代码:

public class Utility {
public static void switchScene(String path) {
Stage stage = getMainStage(); // Assume this returns the primary stage
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource(path));

try {
Parent root = loader.load();
Controller controller = loader.getController();
controller.start();
Scene scene = new Scene(root);
stage.setScene(scene);
} catch (IOException e) {
e.printStackTrace();
}
}
}

我认为这段代码可以工作(我正在让我的 View 的每个 Controller 都实现 Controller 接口(interface),它上面只有一个 start 方法。),但是我收到此错误消息:

java: non-static method getClass() cannot be referenced from a static context

有什么办法可以解决这个问题吗?

最佳答案

不要将路径作为 String。将其更改为 URL

public class Utility {
public static void switchScene(URL path) {
Stage stage = getMainStage(); // Assume this returns the primary stage
FXMLLoader loader = new FXMLLoader();
loader.setLocation(path);

try {
Parent root = loader.load();
Controller controller = loader.getController();
controller.start();
Scene scene = new Scene(root);
stage.setScene(scene);
} catch (IOException e) {
e.printStackTrace();
}
}
}

现在每个人都可以用自己的 fxml 调用它,无论它在哪里,而且签名对参数应该是什么不那么困惑了:

Utility.switchScene(SomeClass.class.getResource("someView.fxml"));

这与您的问题无关,但我还建议您将 Stage 作为参数或通过依赖注入(inject)获取,而不是调用函数 ( Inversion of Control principle ) 并抛出 IOException 而不是捕获它,因为它会通知实用程序类的用户可能出错的方式。我还认为返回 Controller 而不是返回 void 是个不错的主意,这样用户就可以使用它了。

关于切换场景的 JavaFX 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709566/

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