myeclipse生成jar包后不显示图片

骑洋车子不逮把 2015-04-09 10:20:56
我编写了一个swing界面(界面上需要导入一些图片,我用的是相对路径,图片放在和src等同的文件中),然后我生成jar包(我用2345打开能看到图片也在里面),最后打开jar文件,但是jar能运行,但是上面的图片都不显示,求大神帮帮忙,最好能举个简单的例子,万分感谢。

我的向swing界面导入图片的方法是:
JLabel jLabel1;
jLabel1.setIcon(new javax.swing.ImageIcon("Chock.png"));

问题补充:我知道一种就是把图片和jar文件放在相同的文件夹下,但是我不喜欢这种方法。
谁能帮我举个例子吗?
...全文
256 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

try {
InputStream is = Main.class.getResourceAsStream("Chock.png");
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[128];
int length = 0;
while ((length = bis.read(buffer)) > 0) {
baos.write(buffer, 0, length);
}
byte[] result = baos.toByteArray();
ImageIcon icon = new ImageIcon(result, "icon说明或标题");
System.out.println(icon.getIconWidth());
} catch (IOException ioe) {
ioe.printStackTrace();
}

为什么执行这个代码有错误啊

淡定的峰哥 2015-04-10
  • 打赏
  • 举报
回复
用File可以检测一下文件的物理路径,即使文件不存在

 File f = new File("Chock.png1");
        System.out.println(f.getAbsolutePath());
        System.out.println(f.exists());
打印出来的结果与实际的物理路径是有差别的,所以是不靠谱的,可以用下面这种方式,虽然走了点弯路

try {
            InputStream is = Main.class.getResourceAsStream("Chock.png");
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[128];
            int length = 0;
            while ((length = bis.read(buffer)) > 0) {
                baos.write(buffer, 0, length);
            }
            byte[] result = baos.toByteArray();
            ImageIcon icon = new ImageIcon(result, "icon说明或标题");
            System.out.println(icon.getIconWidth());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
suciver 2015-04-10
  • 打赏
  • 举报
回复
你得把你的图片放在和jar同级目录下例如你的jar放在D:\temp那么你的图片也要放在D:\temp

58,454

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧