Gradle Jar按预期工作,但Gradle Run失败

时间:2018-11-02 03:41:50

标签: java gradle javafx jar

我最近想用Gradle构建JavaFX项目的jar。因此,我继续在项目目录中创建了包装器,并将build.gradle文件编辑到下面。

apply plugin: 'java'
apply plugin: 'application'

sourceSets.main.java.srcDirs = ['/']
mainClassName = "Main"

task wrapper(type: Wrapper) {
    gradleVersion = '4.8'
}

jar {
    manifest {
        attributes(
                'Class-Path': '../',
                'Main-Class': 'Main'
        )
    }

    from('/') {
        include 'images/**/*.png'
        include 'images/**/*.jpg'
        include 'styles/css/**/*.css'
        include 'fonts/**/*.TTF'
        include 'fonts/**/*.ttf'
    }
}

使用它,我的编译jar可以按预期工作。没有错误。但是,每当我运行gradlew run时,都会出现以下错误。

Caused by: java.lang.NullPointerException
        at styles.java.TitleStyles.<init>(TitleStyles.java:9)
        at scenes.TitleScene.<init>(TitleScene.java:34)
        at scenes.SceneController.<clinit>(SceneController.java:6)
        ... 14 more

有问题的代码是

private String stylesheet = this.getClass().getResource("/styles/css/TitleStyles.css").toExternalForm();

我的项目结构如下

项目结构图

enter image description here

项目结构图2

enter image description here

关于我为什么无法gradlew run的任何想法?

2 个答案:

答案 0 :(得分:0)

使用gradle run时遇到NullpointerException的原因是因为文件夹结构“ / styles / ....”不在类路径中

要验证这一点..您可以在Main.java中添加以下行:

  

System.out.println(System.getProperty(“ java.class.path”));

并以java -jar的身份运行 和gradle运行 您会发现其中的区别。 TP解决了这个问题,使用标准gradle java文件夹结构:

src 
   - main
   --- java
   --- resources

答案 1 :(得分:0)

这确实是一个类路径问题,但是我还需要做更多的事情来解决我的问题。我必须使用以下结构重新创建gradle项目。

src
  -main
  --java
  ---projectCodeHere

  --resources
  ---nonJavaFileCodeHere

我必须将非Java代码重新定位到资源,否则它不会与.class文件一起复制。 然后我不得不更改代码,使其看起来像这样P

private String stylesheet = getClass().getClassLoader().getResource("css/ConnectionStyles.css").toExternalForm();

此后一切正常。似乎Gradle和IntelliJ对项目的结构很挑剔,而且我找不到改变类路径的“干净”解决方案,所以我最终只是重组了项目,因此我为此感到更高兴。感谢您的帮助!

相关问题