I am trying to read resources for my JavaFX application but it only works, if the module-info
is not defined. If the module-info
is defined, I always receive null
for the following code:
// Replace ... with a specific path, for example: JavaFX_Logo.png
String url = getClass().getResource("...").toExternalForm();
Source tried:
- How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?
- https://github.com/gradle/gradle/issues/890#issuecomment-603289940
MWE: I made an minimal working example in github if someone is interested to see the output. I am using the IDE called IntelliJ and build tool called Gradle (Kotlin DSL).
Example code:
package app;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class App extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
Pane pane = new Pane(root);
String url = getClass().getResource("JavaFX_Logo.png").toExternalForm(); // Returns NPE, because getResource return null
ImageView imageView = new ImageView(url);
pane.getChildren().add(imageView);
Scene scene = new Scene(pane, 1024, 768);
primaryStage.setScene(scene);
primaryStage.show();
}
}
modul-info:
module ExampleFX.main {
requires javafx.graphics;
exports app;
}
Resources to the image: src/main/resources/app/JavaFX_Logo.png
Build structure:
build
┣ classes
┃ ┗ java
┃ ┃ ┗ main
┃ ┃ ┃ ┗ app
┃ ┃ ┃ ┃ ┗ App.class
┣ distributions
┃ ┣ ExampleFX-1.0-SNAPSHOT.tar
┃ ┗ ExampleFX-1.0-SNAPSHOT.zip
┣ generated
┃ ┗ sources
┃ ┃ ┣ annotationProcessor
┃ ┃ ┃ ┗ java
┃ ┃ ┃ ┃ ┗ main
┃ ┃ ┗ headers
┃ ┃ ┃ ┗ java
┃ ┃ ┃ ┃ ┗ main
┣ libs
┃ ┗ ExampleFX-1.0-SNAPSHOT.jar
┣ resources
┃ ┗ main
┃ ┃ ┗ app
┃ ┃ ┃ ┗ JavaFX_Logo.png
┣ scripts
┃ ┣ ExampleFX
┃ ┗ ExampleFX.bat
┗ tmp
┃ ┣ compileJava
┃ ┃ ┗ source-classes-mapping.txt
┃ ┗ jar
┃ ┃ ┗ MANIFEST.MF
Edit:
- Added
modul-info