java - Java Swing Maven - 如何在 jar 文件中加载 ImageIcon
问题描述
这是我当前的目录结构(包含在connect4
目录中):
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── dv
│ │ │ └── app
│ │ │ ├── App.java
│ │ │ ├── Board.java
│ │ │
| | |
│ │ │
│ │ └── resources
│ │ ├── red-chip.png
│ │
│ └── test
│ ...
|
└── target
├── classes/com/dv/app/*.class
本质上Board.java
,我正在尝试访问red-chip.png
.
我尝试了很多变体来实现这一点,现在我只有:
ImageIcon redChip = new ImageIcon("red-chip.png");
我尝试更改使用路径/resources
,使用该getResource
功能,但似乎没有任何效果。
当我使用mvn package
并运行 jar 文件生成 jar 时,它不显示图像。
我执行unzip -l <jar file>
并看到我的 red-chip.png 出于某种原因已移至根目录。
Length Date Time Name
--------- ---------- ----- ----
126 2019-05-30 20:03 META-INF/MANIFEST.MF
0 2019-05-30 20:03 META-INF/
0 2019-05-30 19:19 com/
0 2019-05-30 19:19 com/dv/
0 2019-05-30 19:20 com/dv/app/
0 2019-05-30 20:03 META-INF/maven/
0 2019-05-30 20:03 META-INF/maven/com.dv.app/
0 2019-05-30 20:03 META-INF/maven/com.dv.app/connect4/
4190 2019-05-30 19:20 com/dv/app/App.class
4975 2019-05-30 19:20 com/dv/app/Board.class
110 2019-05-29 20:29 META-INF/maven/com.dv.app/connect4/pom.properties
7856 2019-05-30 19:32 red-chip.png
这是我的pom.xml
。主要看的是构建 jar 插件。
(删除了artifactID等无用的东西)
<project xmlns="...">
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.dv.app.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
所以我的问题如下:
引用我的 png 文件以使其在 jar 中可见的正确方法是什么?
为什么 png 文件位于 jar 的根目录中?
解决方案
如果您需要将图像加载为应用程序的图标,您的代码应该是这样的。这将为您的应用程序设置图标。
this.setIconImage(new ImageIcon(getClass().getResource("/red-chip.png")).getImage());
如果需要使用setIcon
方法,可以使用
ImageIcon IC = new ImageIcon(getClass().getResource("/red-chip.png"));
推荐阅读
- twilio - 我应该将通过 twilio 消息 (whatsapp) 发送的媒体(图像、png、...)的外部链接保留多长时间?
- asynchronous - 测试异步回复的机制
- java - Spring 可缓存对象存储在哪里?
- swift - 结合订阅和从主题发送,为什么顺序很重要?
- python - 在字典中创建嵌套列表,列表中没有重复项
- java - java中的同步概念不起作用?
- c# - 检查 GridView 中的列是否有位图
- docker - Kubernetes & Gitlab:如何存储私有注册表的密码?
- python - pyspark 中 spark.sql() 和 cursor.execute 的区别?
- typescript - 如何让 ts-transformer-keys 与 Vue 一起使用