切换场景的JavaFX问题

时间:2016-11-20 21:26:44

标签: java javafx static

我有一个Utility课程,我正在尝试创建名为static的{​​{1}}方法,以便能够轻松切换舞台中的场景。这是我尝试使用的代码:

switchScene

我认为这段代码可行(我正在为我的视图制作每个控制器实现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(); } } } 接口,它只有一个Controller方法。)但是我收到此错误消息:< / p>

start

我能做些什么来解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

如果您想在getClass()方法中调用static,则需要将其与类名一起使用,因此您需要更改代码,如下所示:

loader.setLocation(Utility.class.getClass().getResource(path));

答案 1 :(得分:2)

不要将路径作为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作为参数或通过依赖注入而不是调用函数(Inversion of Control principle)并抛出IOException而不是捕获它,因为它告诉实用工具类的用户可能出现问题的方法。我还认为返回Controller而不是返回void以便用户可以使用它并不是一个坏主意。