Search code examples
javafxfxml

What is wrong with this FX Application?


I am hours trying to know why this code is wrong, it gives me an Exception, the GUI.fxml is on the root of the project.

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);
    }
}

Already searched a lot, no solution found yet.

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$000(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl$1.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$5.run(LauncherImpl.java:319)
    at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:219)
    at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:182)
    at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl$4.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.access$100(WinApplication.java:17)
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
    ... 1 more

Solution

  • The FXML should not be in the root of the project, but in the classpath. Try relocating the fxml into a source folder.

    For general projects, you have a src folder. You can also create your own custom source folder also.

    For maven projects, you can try keeping them inside src/main/resources.