我正在 Windows 10 上使用 Gradle 构建 JavaFx 应用程序。我使用 Gradle init 任务创建了该项目,因此目录结构为
src
|--- main
|--- java
| |--- thomas/software/helloworld/App.java (Main class)
| |--- thomas/software/helloworld/MainViewController.java (extends JavaFX Application)
|--- resources
|--- imgs/ (some images)
|--- layout/ (fxml files)
在我的 Controller 中,我尝试加载布局文件:
FXMLLoader loader = new FXMLLoader(
getClass().getResource("../../../layout/main.fxml").toURI().toURL());
我加载这样的图像:
path = getClass().getClassLoader().getResource("imgs/question.png").toExternalForm();
当我使用 gradle run
或 gradlew run
运行项目时,这两种方法可以互换使用。
我的问题是,当我运行 gradlew distZip
生成的分发版时,从生成的批处理文件运行找不到布局文件并引发空指针异常。
build/libs 中生成的 jar 文件和 build/distributions 中的 zip 文件的结构是相同的,如下所示:
imgs/ (images are there)
layout/ (layout file also there)
META-INF/
thomas/software/helloworld/ (everything there as well)
这是我的 build.gradle 文件:
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* User Manual available at https://docs.gradle.org/6.1/userguide/tutorial_java_projects.html
*/
plugins {
// Apply the java plugin to add support for Java
id 'java'
// Apply the application plugin to add support for building a CLI application.
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.8'
}
javafx {
version = "13"
modules = ['javafx.controls', 'javafx.fxml']
}
tasks.withType(JavaExec) {
if (System.getProperty('DEBUG', 'false') == 'true') {
jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9099'
}
}
repositories {
// Use jcenter for resolving dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// This dependency is used by the application.
implementation 'com.google.guava:guava:28.1-jre'
// Use JUnit Jupiter API for testing.
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2'
// Use JUnit Jupiter Engine for testing.
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.2'
}
application {
// Define the main class for the application.
mainClassName = 'thomas.software.helloworld.App'
}
test {
// Use junit platform for unit tests
useJUnitPlatform()
}
Java 版本 13
Gradle 版本 6.1。
我缺少什么?
最佳答案
谢谢@Slaw 和@Compass。它与.代码的相关部分:
var instream = getClass().getClassLoader().getResourceAsStream("layout/main.fxml");
FXMLLoader loader = new FXMLLoader();
loader.setController(this);
loader.load(instream);
关于java - getClass().getResource() 仅适用于 Gradle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867387/