且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaFX 11:使用 Gradle 创建 jar 文件

更新时间:2021-07-15 01:27:44

如果有人感兴趣,我找到了一种为 JavaFX11 项目(使用 Java 9 模块)创建 jar 文件的方法.我仅在 Windows 上对其进行了测试(如果该应用程序也适用于 Linux,我认为我们必须执行相同的步骤,但在 Linux 上才能获得适用于 Linux 的 JavaFX jar).

If someone is interested, I found a way to create jar files for a JavaFX11 project (with Java 9 modules). I tested it on Windows only (if the application is also for Linux, I think we have to do the same steps but on Linux to get JavaFX jars for Linux).

我有一个Project.main"模块(由 IDEA 创建,当我创建 Gradle 项目时):

I have a "Project.main" module (created by IDEA, when I created a Gradle project) :

 src
 +-- main
 |   +-- java
     |   +-- main
         |   +-- Main.java (from the "main" package, extends Application)
     |   +-- module-info.java
 build.gradle
 settings.gradle
 ...

module-info.java 文件:

The module-info.java file :

module Project.main {
    requires javafx.controls;
    exports main;
}

build.gradle 文件:

The build.gradle file :

plugins {
    id 'java'
}

group 'Project'
version '1.0'
ext.moduleName = 'Project.main'
sourceCompatibility = 1.11

repositories {
    mavenCentral()
}

def currentOS = org.gradle.internal.os.OperatingSystem.current()
def platform
if (currentOS.isWindows()) {
    platform = 'win'
} else if (currentOS.isLinux()) {
    platform = 'linux'
} else if (currentOS.isMacOsX()) {
    platform = 'mac'
}
dependencies {
    compile "org.openjfx:javafx-base:11:${platform}"
    compile "org.openjfx:javafx-graphics:11:${platform}"
    compile "org.openjfx:javafx-controls:11:${platform}"
}

task run(type: JavaExec) {
    classpath sourceSets.main.runtimeClasspath
    main = "main.Main"
}

jar {
    inputs.property("moduleName", moduleName)
    manifest {
        attributes('Automatic-Module-Name': moduleName)
    }
}

compileJava {
    inputs.property("moduleName", moduleName)
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
                '--add-modules', 'javafx.controls'
        ]
        classpath = files()
    }
}

task createJar(type: Copy) {
    dependsOn 'jar'
    into "$buildDir/libs"
    from configurations.runtime
}

settings.gradle 文件:

The settings.gradle file :

rootProject.name = 'Project'

和 Gradle 命令:

And the Gradle commands :

#Run the main class
gradle run

#Create the jars files (including the JavaFX jars) in the "build/libs" folder
gradle createJar

#Run the jar file
cd build/libs
java --module-path "." --module "Project.main/main.Main"