JavaFX和Gradle中的NullPointerException和Resource目录(通过jar文件分发)

时间:2019-05-27 01:09:31

标签: gradle javafx

我正在构建在Gradle中生成的JavaFX应用程序,以了解有关在Java中构建GUI应用程序的更多信息。我遇到的一个难题是要访问一个要在媒体视图中显示的.mp4文件。该应用程序的目的是通过.jar文件运行,除了文件参考打ic之外,我已经能够大致上使用JavaFX 12。

我已引用this Stack Overflow post,其解决方案在我的项目中仍返回Null指针。使用

def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    context = {
        "posts": posts,
    }
    return render(request, "blog_index.html", context)


def blog_category(request, category):
    posts = Post.objects.filter(
        categories__name__contains=category
    ).order_by(
        '-created_on'
    )
    if not posts:
        return HttpResponse(status=404)

    context = {
        "category": category,
        "posts": posts
    }
    return render(request, "blog_category.html", context)

def blog_detail(request, pk):
    post = Post.objects.select_related().get(pk=pk)
    print(post.categories.name) # Returns None!!
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)

可以工作,但随后会以jar格式产生媒体异常。

文件结构如下:

Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();

gradle构建文件为:

.
build.gradle
src
|─── main
     |───java
         |───hellofx
             |─── HelloFX.java
             |─── Launcher.java
     |─── resources
          |─── hellofx
               |─── video.mp4

Java代码为:

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) }
    }
}

1 个答案:

答案 0 :(得分:0)

对此有一个简单的解释。您正在尝试解析路径,但是如果将它协定成一个jar文件,这会很复杂。

因此,如果要将mp4文件放入罐子中,请执行与 boop.txt Blend_W-gladRLvno7U.mp4 类似的操作资源也可以在包装好的罐子中使用。

基本上就是这样:

this.getClass().getClassLoader().getResource("/hellofx/Blend_W-gladRLvno7U.mp4");

这应该可以解决问题:)