You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Maven打包Swing集成JavaFX的可运行jar时JFXPanel实例化报错

问题原因

你当前打包生成的jar仅包含项目自身代码,未将依赖的JavaFX相关类库打包到jar内,所以运行时会找不到javafx.embed.swing.JFXPanel类。同时你当前pom中JavaFX依赖版本不统一,javafx-controls、javafx-fxml用的是13版本,javafx-swing用的是18预览版,也可能引发兼容性问题。

修复步骤

1. 统一JavaFX依赖版本

将pom.xml中所有JavaFX依赖调整为同一个正式发布版本,示例使用17 LTS版本:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>17.0.8</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>17.0.8</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-swing</artifactId>
        <version>17.0.8</version>
    </dependency>
</dependencies>

同时根据你使用的JDK版本调整编译参数,比如用JDK17就把properties里的编译版本修改为:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>

2. 替换打包插件为maven-shade-plugin

原来的maven-jar-plugin仅会打包项目自身的类,不会引入依赖。使用maven-shade-plugin可以将所有依赖打包到同一个jar内(即fat jar)。
在pom.xml的build节点下新增plugins节点(不要只放在pluginManagement内,否则不会生效),添加如下配置:

<build>
    <pluginManagement>
        <!-- 原有pluginManagement内的配置保持不变 -->
    </pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.4.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>com.carrier.ccr.test.App</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3. 重新打包运行

执行mvn clean package命令打包,完成后target目录下会生成名字带shaded后缀的jar包,执行如下命令运行即可:

java -jar test-0.0.1-SNAPSHOT-shaded.jar

额外说明

如果运行时仍报JavaFX模块相关错误,可以在运行命令中添加模块参数,替换为你本地JavaFX SDK的lib路径即可:

java --module-path /your/javafx-sdk/lib/path --add-modules javafx.controls,javafx.fxml,javafx.swing -jar test-0.0.1-SNAPSHOT-shaded.jar

内容的提问来源于stack exchange,提问作者Felix D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:57:03