2

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:

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
Nyanyan
  • 43
  • 5
  • Did you create your own module-info.java or is it generated by gradle? – dan1st Apr 02 '21 at 20:18
  • I've created my own. I forgot to add it on the github repositoy and on my question. I added it now. – Nyanyan Apr 02 '21 at 21:00
  • 1
    I'm not sure the `org.openjfx.javafxplugin` is compatible with the module handling added in Gradle 6.4. Does the problem occur if you remove the JavaFX plugin and add the JavaFX dependencies manually? Note you need the appropriate classifier (e.g. `org.openjfx:javafx-base::win` for Windows); unfortunately, the classifier breaks transitive dependency resolution in Gradle so you'll have to add each JavaFX dependency explicitly. – Slaw Apr 02 '21 at 21:31
  • Sorry for the late response because I had some upcoming exams. Your answer solved the problem. Thanks a lot! – Nyanyan Apr 11 '21 at 13:54

0 Answers0