图片里面的.jar文件不会工作,当我导出它 [英] Picture inside .jar file wont work when I export it

查看:147
本文介绍了图片里面的.jar文件不会工作,当我导出它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个显示图片的Java程序,并且它在Eclipse中很好地工作,但是当我将它导出到.jar文件时,它不会显示图片。我刚开始学习Java,而且我没有在jar文件中创建Jar文件和使用文件的经验。

I made a Java program that displays a picture, and it works perfectly in Eclipse, but when I export it to a .jar file, it wont display the picture. I just started learning Java, and I have no experience with creating Jar files and using files from inside the jar file.

我的代码:

import javax.swing.*;
class displayPicture{
public static void main(String args[]){


    JFrame frame = new JFrame();
    ImageIcon icon = new ImageIcon("src/img.gif");
    JLabel label = new JLabel(icon);

    //Create the frame
    frame.add(label);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}
}

当我运行时显示图片它在Eclipse中,但是当我将它导出到.jar文件时,它只显示一个空白窗口。

It shows the picture when I run it in Eclipse, but when I export it to a .jar file, it just shows a blank window.

推荐答案

两件事...

/ strong>

First

代码构建后,路径 src 不太可能存在

The path src is unlikely to exist once the code is build

第二个

Second

ImageIcon(String) String 引用是对文件系统上文件的引用。存储在应用程序上下文中的资源不是文件,而是受到不同的对待。它们通常被称为嵌入式资源。

ImageIcon(String) assumes the String reference is a reference to a file on the file system. Resources stored within the context of the application are not files and are treated differently. They are commonly known as embedded resources.

相反,请尝试使用 ImageIcon icon = new ImageIcon(displayPicture.class.getResource(img.gif )); ImageIcon icon = new ImageIcon(displayPicture.class.getResource(/ img.gif));

我喜欢使用 ImageIO.read ,因为它会抛出一个 IOException 出现错误并支持更多文件格式。

I prefer to use ImageIO.read as it throws an IOException when something goes wrong and supports more file formats.

请参阅阅读/加载图片了解更多详情。

您还应该花时间阅读 Java编程语言的代码约定初始线程

You should also take the time to have a read through Code Conventions for the Java Programming Language and Initial Threads

这篇关于图片里面的.jar文件不会工作,当我导出它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆