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

如何在IntelliJ中用Maven为Swing项目构建可运行FatJar

解决方案:构建可双击运行的Swing FatJar

1. 配置Maven Shade插件(核心步骤)

maven-shade-plugin是生成FatJar的标准工具,能把项目代码、所有依赖、资源文件打包到单个Jar中,同时指定主类让Jar支持双击运行。将以下配置插入到pom.xml的<build><plugins>节点内:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.5.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <!-- 替换为你的主类全路径,比如com.myapp.SwingMain -->
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>你的主类全限定名</mainClass>
                    </transformer>
                    <!-- 处理Swing相关资源冲突 -->
                    <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/services/javax.swing.plaf.basic.BasicLookAndFeel</resource>
                    </transformer>
                </transformers>
                <!-- 排除签名文件避免打包冲突 -->
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>

关键注意点:必须将<mainClass>的内容替换为你实际的主类全路径(比如主类在com.demo包下,类名为MySwingApp,则填写com.demo.MySwingApp)。

2. 确保依赖的表格文件被正确打包

将你的表格文件移入项目的src/main/resources目录(没有则手动创建),Maven会自动将该目录下的文件打包到Jar中。代码中读取文件时,使用类加载器方式避免路径问题:

// 示例:读取resources根目录下的table.xlsx
InputStream tableStream = getClass().getResourceAsStream("/table.xlsx");
// 如果表格在resources的子目录,比如data/table.xlsx,路径写"/data/table.xlsx"

3. 执行Maven打包命令

在IntelliJ的Terminal中运行:

mvn clean package

打包完成后,target目录下会生成两个Jar:

  • 普通瘦Jar(名称类似your-project-1.0-SNAPSHOT.jar)
  • 带-shaded后缀的FatJar(比如your-project-1.0-SNAPSHOT-shaded.jar)—— 这个就是可双击运行的目标文件。

4. 排查运行问题

如果双击Jar无反应,打开控制台运行命令查看报错:

java -jar target/your-project-1.0-SNAPSHOT-shaded.jar

常见问题包括:主类路径错误、资源文件读取路径错误、依赖缺失(需检查pom.xml的依赖是否完整)。

5. IntelliJ图形化打包(可选)

若偏好使用界面操作:

  1. 打开File > Project Structure > Artifacts
  2. 点击+选择JAR > From modules with dependencies
  3. 选择主类,勾选Include in project build,配置资源文件输出路径
  4. 点击Build > Build Artifacts选择对应Jar构建

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:05:15