这个 FX 应用程序有什么问题?

What is wrong with this FX Application?

我花了好几个小时想知道为什么这段代码是错误的,它给了我一个异常,GUI.fxml 在项目的根目录上。

public class MyApp extends Application{

        @Override
        public void start(Stage primaryStage) throws Exception {
            String location = "/GUI.fxml";
            Parent root = FXMLLoader.load(getClass().getResource(location));

            primaryStage.setScene(new Scene(root,300,450));
            primaryStage.setTitle("Minha Janela");
            primaryStage.show();
        }

    public static void main(String[] args) {
        launch(args);
    }
}

已经找了很多,还没有找到解决方案。

Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
    at com.sun.javafx.application.LauncherImpl.access[=11=]0(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl.run(LauncherImpl.java:115)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2825)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2809)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2795)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2782)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2771)
    at g1.MyApp.start(MyApp.java:13)
    at com.sun.javafx.application.LauncherImpl.run(LauncherImpl.java:319)
    at com.sun.javafx.application.PlatformImpl.run(PlatformImpl.java:219)
    at com.sun.javafx.application.PlatformImpl.run(PlatformImpl.java:182)
    at com.sun.javafx.application.PlatformImpl.run(PlatformImpl.java:179)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.run(PlatformImpl.java:179)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access0(WinApplication.java:17)
    at com.sun.glass.ui.win.WinApplication.run(WinApplication.java:67)
    ... 1 more

FXML 不应在项目的根目录中,而应在 classpath 中。尝试将 fxml 重新定位到源文件夹中。

对于一般项目,您有一个 src 文件夹。您也可以创建自己的自定义源文件夹。

对于maven项目,你可以试着把它们放在src/main/resources.

里面