I am building a JavaFX application that is produced in Gradle to learn more about the process of building GUI applications in Java. A bump in the road that I have encountered involves accessing a .mp4 file to be displayed in the Media View. The intention is for this app to run through a .jar file, which I have been able to get to work with JavaFX 12 in general aside from the file reference hiccup.
I have referenced this Stack Overflow post and its solution still returns a Null Pointer in my project. Using
Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();
does work, but will then yield a Media Exception in the jar format.
The file Structure is as follows:
.
build.gradle
src
|─── main
|───java
|───hellofx
|─── HelloFX.java
|─── Launcher.java
|─── resources
|─── hellofx
|─── video.mp4
The gradle build file is:
plugins {
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.7'
}
repositories {
mavenCentral()
}
sourceSets {
main {
resources {
srcDirs = ["src/main/resources"]
includes = ["**/*.mp4"]
}
}
}
dependencies {
/* uncomment for cross-platform jar: */
runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:win"
// runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:linux"
// runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:mac"
}
javafx {
version = "12.0.1"
modules = [ 'javafx.controls','javafx.fxml','javafx.media' ]
}
mainClassName = 'hellofx.HelloFX'
jar {
manifest {
attributes 'Main-Class': 'hellofx.Launcher'
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
And the Java Code is:
public void start(Stage stage) {
//Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));
// Create and set the Scene.
Scene scene = new Scene(new Group(), 640, 360);
stage.setScene(scene);
//Returns Null Here (resource)
final URL resource = HelloFX.class.getResource("imgs/Blend_W-gladRLvno7U.mp4");
//Returns Null here (loc)
URL loc = this.getClass().getClassLoader().getResource("boop.txt");
System.out.println(loc);
String test = Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();
System.out.println(test);
//Set up Media
Media media = new Media(test);
// Create the player and set to play automatically.
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
// Create the view and add it to the Scene.
MediaView mediaView = new MediaView(mediaPlayer);
((Group) scene.getRoot()).getChildren().add(mediaView);
stage.setTitle("JavaFX and Gradle");
stage.setScene(scene);
stage.show();
}