Exception in application start method javafx ошибка

Воспроизводил аналогичную ошибку, используя Java 11 & Java FX 11 & Intelij IDEA 2021.1.1:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3230)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
    at sample.Main.start(Main.java:13)
    at 

И проблема была в том, что при дефолтном генерировании JavaFX проекта средой разработки файл fxml был расположен в директории:

src/main/java/.../sample.fxml

когда перенёс fxml файл по совету тут и тут в:

src/main/resources/sample.fxml

и в start() методе прописал:

Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));

пофиксилось.

При написании своего приложения на JavaFX столкнулся с ошибкой

Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
…..

Дело в том, что когда мы добавляем в проект библиотеки JavaFX необходимо чтобы при компиляции и отладке пути к модулям и перечень используемых модулей передавались как параметры в java.exe.

Чтобы ошибка исчезла в Intellij IDEA заходим в Run – Edit configurations . В VM options прописываем строку

–module-path C:Javajavafx-sdk-13.0.2lib –add-modules ALL-MODULE-PATH

Вместо C:Javajavafx-sdk-13.0.2 укажите путь до папки с SDK.

Вместо ALL-MODULE-PATH можете указать перечень модулей, например javafx.controls, javafx.fxml

Why exception in java lang reflect invocationtargetexception is happeningThe exception in application start method java.lang.reflect.InvocationTargetException is an error code that occurs when you are using JavaFX. There are myriad situations that cause this error. Keep on reading, as we’ll give you detailed explanations of these causes and their fix.

By the end of this article, you’ll know how to prevent and fix the error in your future JavaFX projects.

Contents

  • Why Exception in Java.lang.reflect.invocationtargetexception is Happening?
    • – Having a Starting Forward Slash in the Pathname of Your Fxml File
    • – Missing Javafx Modules
    • – Using Dynamic Root Without Setting the Root on the Fxmlloader
  • How To Fix the Exception in Application Error?
    • – Remove the Forward Slash in the Path Name of the Fxml File
    • – Update Intellij Idea To Use Javafx Modules Via the vm Options
    • – Set the Root on Fxmlloader Before Loading the Fxml File
  • Conclusion

You have an exception in java.lang.reflect.InvocationTargetException because of the following:

  • You have a starting forward slash in the pathname of your FXML file
  • You are missing JavaFX modules
  • You are using dynamic root without setting the root on the FXMLLoader

– Having a Starting Forward Slash in the Pathname of Your Fxml File

A forward slash in the pathname of your FXML file can cause an exception in JavaFX. For example, the following code can trigger the exception:

FXMLLoader loader = new FXMLLoader(Main.class.getResource(“/File.fxml”));

When you check the previous code, you’ll note that we have a forward slash before the FXML file. Though this will work on some systems, but on most systems, it’ll cause an exception.

– Missing Javafx Modules

Missing JavaFX modules when running JavaFX can cause an exception. The “Getting Started with JavaFX” on OpenJFX outlined steps for a JavaFX project with IntelliJ IDEA. Check the below points:

  • Create a JavaFX project
    • At this stage, you give your project a name
    • Give the project a location
  • Set JDK 17
    • You do this by navigating to File → Project Structure → Project
    • Also, you can set the language level to a minimum value of 11
  • Create a library
    • Navigate to File → Project Structure → Libraries
    • Add JavaFX 17 SDK as a library
    • Point to the lib folder of the SDK
      • Once you apply the library, IntelliJ will recognize the JavaFX classes

If you perform all the operations outlined in the previous steps, your code will compile but you’ll get an error. That’s because IntelliJ does not include some modules that’ll make your code work. For the code to work, you have to tell Java which modules it’ll use for your application.

Keep on reading, as we’ll explain how you can fix this in the “How To Fix” section.

– Using Dynamic Root Without Setting the Root on the Fxmlloader

You’ll raise an exception if you use the dynamic root <fx:root type=”AnchorPane”> without setting the root on the FXMLLoader. That’s because < fx:root> specifies a dynamic root for your FXML file. So, its root is an object that you must set before loading the FXML file. Meanwhile, a use case for this is when you want to define the layout of custom controls with FXML.

For example, an exception occurs in the following public class. This class extends the Application class in JavaFX:

public class HelloWorld extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“MyFXMLDoc.fxml”));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}

In the above-mentioned code, we’ve called the load() method of FXMLLoader on the FXML file but we did not set any root before trying to load the FXML file. As a result, the code causes an exception.

How To Fix the Exception in Application Error?

You can fix the exception by updating your code or adding the required JavaFX modules. As a result, your code will work as expected. However, it’s easier said than done. In this section, we’ll go into detail on how to fix and prevent the exception in your project.

– Remove the Forward Slash in the Path Name of the Fxml File

When you load your FXML file with FXMLLoader, observe if there is a forward slash in the pathname of the FXML file. If you are getting an exception, remove this forward slash. Afterward, your code should work. For example, the following is a code we showed you earlier:

FXMLLoader loader = new FXMLLoader(Main.class.getResource(“/File.fxml”));

From the code, we have the forward slash before File.fxml but in the code below, we’ve eliminated the forward slash. So, your code should work.

// Take out the “/” before the FXML file

FXMLLoader loader = new FXMLLoader(Main.class.getResource(“File.fxml”));

There are cases where the absence of the forward slash caused an exception. So, if you are in such a situation, add the forward slash to prevent the exception.

– Update Intellij Idea To Use Javafx Modules Via the vm Options

In IntelliJ IDEA, you’ll need to add the JavaFX modules as a VM option based on your Operating System. We say “JavaFX modules” because JavaFX is a collection of modules. We base this solution on the “Getting Started” tutorial on OpenJFX. Earlier, we mentioned that if you compile your code without the JavaFX modules, you’ll get an error.

To add the VM options, go to the following location in IntelliJ IDEA:

Run → Edit Configurations

At the above location, if you are on Windows, add the VM options using the following:

–module-path “pathtojavafx-sdk-17.0.1lib” –add-modules javafx.controls,javafx.fxml

If you are on Linux or Mac, use the following:

–module-path /path/to/javafx-sdk-17.0.1/lib –add-modules javafx.controls,javafx.fxml

As an alternative, you can define a global variable for future projects. To get started, navigate the following path in IntelliJ:

  1. Preferences (File → Settings) → Appearance & Behavior → Path Variables
  2. Define the variable name as PATH_TO_FX
  3. Browse to the lib folder of the JavaFX SDK to set its value
  4. Click apply

Afterward, you can refer to this global variable when you set the VM options:

–module-path ${PATH_TO_FX} –add-modules javafx.controls,javafx.fxml

Once you’ve added the VM options, run your project, and your code should work fine.

The project created on the OpenJFX tutorial is the default project that uses FXML therefore, your code requires javafx.fxml and javafx.controls. Note that if your project uses other modules, you should add them. So, after adding the modules, save your settings.

– Set the Root on Fxmlloader Before Loading the Fxml File

To prevent the exception, you should set the root on FXMLLoader before you load your FXML file. The next code block is a sample class that we discussed earlier. In the code, we did not set the root before loading the FXML file. As a result, we get an error.

public class HelloWorld extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“MyFXMLDoc.fxml”)); // Where the error occurred
Scene scene = new Scene(root);
stage.setScene(scene); stage.show();
}
}

However, in our next code, we’ve made corrections. The corrections ensure the proper use of <fx:root> which are the following:

  • Create an FXMLLoader instance
  • Call setRoot() on the instance
    • Pass in the root object of the FXML

public class HelloWorld extends Application {
@Override
public void start(Stage stage) throws Exception {
// Create an FXMLLoader Instance
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(“MyFXMLDoc.fxml”));
// Call setRoot on the instance
fxmlLoader.setRoot(new AnchorPane());
// Call the load() function on the file
Parent root = fxmlLoader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}

Conclusion

This article explained how to fix the causes of the exception when you are using JavaFX. We provided coding examples and explained solutions with actionable steps to identify and solve the issue. Here are the summary of the most important points that we talked in the article:

  • A starting forward slash in the path name of an FXML file can cause an exception.
  • Not setting the root before loading the XML file leads to an exception.
  • To prevent an exception when working with JavaFX in IntelliJ, use JavaFX modules.
  • You can add JavaFX modules as VM options in IntelliJ IDEA.
  • You can prevent the failure from happening by setting the root on FXMLLoader before you load your FXML file.

How to fix the exception in application errorAt this stage, you have what it takes to fix the exception in your application and run an error-free code.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Fix JavaFx Exception in Application Start Method

JavaFX is a highly enriched library whose code gets written in native Java code. The library gets used to making Rich Internet Applications, often known as RIA.

The library is a set of interfaces and classes that are easily understandable and are a friendly alternative to Java Virtual Machine or JVM. The code written using the library can run across multiple platforms without fail like desktops, mobiles, televisions, etc.

Long back, the graphical User Interface gets built using Swing templates, but after the advent of JavaFX, one can easily rely on the language to work over the same. The applications built using JavaFx have a penetration rate of 76 percent.

The Exception in Application start method is the runtime error that occurs when the application is running and when compilation gets done. The state occurs when the application is inefficient in loading runtime variables or files. It can throw NullPointerException, FileNotFound type of exceptions when not handled properly.

Additionally, plugins like SonarLint, programming mistake detector(PMD), find bugs can help identify the runtime issues beforehand without actual program runs.

Below is an example to show the Exception in Application start method error in JavaFx.

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class ApplicationStart extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent parent = FXMLLoader.load(getClass().getResource("AnyXML.fxml"));
        Scene scene = new Scene(parent);
        stage.setScene(scene);
        stage.setTitle("First Swing Sample");
        stage.show();
    }
}

The above source code that seems to be in JavaFx has a main method in the ApplicationStart class. The given class extends an abstract Application class and is specifically available in JavaFX Library.

It has a default theme called Caspein that gets launched once you start the application. The launch is a static method present in the Application class and gets called from the main function. It takes variable arguments or varargs as its parameters. It throws IllegalStateException if the launch method gets called more than once.

The Application class has one abstract method whose implementation must be present in ApplicationStart class. The override annotation shows that the code below the annotation belongs to the parent Application class. The implementation of the method that gets proceeded by the annotation override is present below the annotation.

The start method is the main entry for the JavaFX applications, as main is the entry location for the Java applications. The main method gets first called when the Application or main thread gets initialized.

The function takes Stage as the parameter. The Stages denotes the primary step or view and gets loaded when the application launches in the applet viewer. It also throws Exception that gets defined along with the method.

The first statement inside the method is to load the XML file. The FXMLLoader class loads an object hierarchy from the XML object model. It gets used to bring the object hierarchy from an FXML document into a Parent instance. It takes the parameter as the URL to the location where the XML document hierarchy is present.

The resultant gets stored in a Parent class instance that holds the subtypes in the graph format. The Scene class present in the JavaFX library is the container unit that stores all the data in a graph view. The background of the scene gets filled by the specified property. The instance of Stage class gets created and can get used with other properties.

Below mentioned are the properties used to display the scene over the browser.

  • The setScene method makes its use to specify the scene and gets used along with the stage instance variable.
  • The setTitle function gets used to set scene title present over the browser. The show function gets used to populate the scene over the stage.

Below is the output for the above code block.

Exception in Application start method
java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
	at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:873)
Caused by: java.lang.RuntimeException: Exception in Application start method
	at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
	at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: Location is required.
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
	at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
	at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
	at ApplicationStart.start(ApplicationStart.java:15)
	at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
	at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
	at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
	at java.security.AccessController.doPrivileged(Native Method)
	at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
	at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
	at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177)
	... 1 more
Exception running application ApplicationStart

In the output shown above, the issue gets raised at the parameter position that uses the FXMLLoader class to load the XML object, but it returns a null value. In simple words, the getResource() method does not locate the path provided in the function parameter.

Hence, the null value populates NullPointerException, which is a type of runtime exception. And are handled by giving an absolute path where the file can get located. The stack trace often shows the line number where the issue starts populating. The target must be correct when get given in the load parameter.

Hence the given solution to the problem is below.

  1. Give the absolute path to the location where the file gets present.
  2. Add a SonarLint plugin to the Integrated Development Environment that helps in evaluating or handling the exceptions at the write time.

Всем доброй ночи!
Как-то странно название решённой задачи отображается — на всякий случай — решаю «Цвета радуги».
JavaFX добавила, в VM options прописано так:

--module-path "C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2021.2.3JavaRushTasksjavafx-sdk-17.0.1lib" --add-modules=javafx.controls,javafx.fxml,javafx.base

5 задач уровня решила в IDE без проблем, а на 6-й словила вот это 😕:

Exception in Application start method
Exception in thread "main" java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
	at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 7
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
	at java.base/java.util.Objects.checkIndex(Objects.java:359)
	at java.base/java.util.ArrayList.get(ArrayList.java:427)
	at com.javarush.games.minigames.mini05.RainbowGame.initialize(RainbowGame.java:32)
	at com.javarush.engine.cell.Game.start(Game.java:68)
	at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
	at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
	at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
	... 1 more

Process finished with exit code 1

На форумах пишут разное, пока не могу сама разобраться…

Понравилась статья? Поделить с друзьями:
  • Exception access violation как исправить ошибку
  • Except python типы ошибок
  • Excel логи ошибок где
  • Excel команда если ошибка
  • Excel как пропустить все ошибки