getting java.lang.reflect.InvocationTargetException while adding a button to layout

From the error I’m assuming you’re using JavaFX 11 (or at least JavaFX 9+). Note that the ultimate problem is not the InvocationTargetException but the IllegalAccessError:

Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module @0x46b3f4cf) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module @0x46b3f4cf

This is telling you code in the “unnamed module” is trying to access internals of the javafx.graphics module. As this is not allowed the error is thrown. But the real problem here is that ControlHelper is in the unnamed module but it’s supposed to be in the javafx.controls module, if the package name is anything to go by. This problem is caused by having javafx.graphics on the modulepath but javafx.controls on the classpath.

Make sure you have both modules (and javafx.base) on the --module-path. As your code is not modular (no module-info file) you will also have to tell the module system to resolve it by using:

--add-modules javafx.controls

You don’t have to include javafx.graphics in the --add-modules command because javafx.controls requires javafx.graphics (and javafx.graphics requires javafx.base). As all modules are on the modulepath they will be resolved.

How you set these commands is dependent on how you launch your application (e.g. command-line, IDE, Maven, Gradle, etc…).

If you ever make your code modular you won’t need to use the --add-modules command, just put the appropriate requires directives in your module-info file. For example:

module app {
    requires javafx.controls;
}

Leave a Comment