简体   繁体   English

导出不与ImageIcon一起使用的可运行Jar

[英]Exporting Runnable Jar Not Working with ImageIcon

I am having a issues with running a runnable jar file which has a image icon in it. 我在运行带有图像图标的可运行jar文件时遇到问题。

Code runs on eclipse nicely and displays the icon in a JFrame . 代码可以在eclipse上很好地运行,并在JFrame显示图标。 The way I add it is by adding it to a JLabel and then adding that JLabel to the JFrame . 我添加它的方法是将其添加到JLabel ,然后将该JLabel添加到JFrame I export the project into a runnable Jar file and when I double click the jar. 我将项目导出到可运行的Jar文件中,然后双击jar。 It doesn't run. 它没有运行。

I tested out just adding a normal JLabel onto the JFrame without the icon code and it works when I exported and ran it. 我进行了测试,只是将普通的JLabel添加到了没有图标代码的JFrame上,并且在导出并运行它时可以正常工作。

Whenever I add the following line to code, it messes the runnable Jar File. 每当我将以下行添加到代码中时,它就会混乱可运行的Jar文件。

JLabel s1 = new JLabel(new ImageIcon(getClass().getResource("/Images/Pattern1.png"))); 

I noticed it could be something wrong when it gets the resources. 我注意到获取资源时可能出错。 My Image Pattern1, is stored in a folder called Images and that folder is inside my project src folder. 我的图像Pattern1存储在一个名为Images的文件夹中,并且该文件夹位于我的项目src文件夹中。 So I am sure it's in the runnable jar file when I export it. 因此,我可以确定导出该文件时该文件位于可运行的jar文件中。

Here my code 这是我的代码

package main;


import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class MyFrame extends JFrame {    

    public MyFrame() {
        JLabel s1 = new JLabel(new ImageIcon(getClass().getResource("/Images/Pattern1.png")));
        this.add(s1);

        //JLabel test = new JLabel("Test");
        //this.add(test);

    }

    public static void main(String[] args) {
        MyFrame f = new MyFrame();
        f.pack();
        f.setVisible(true);
    }
}

This is what my files in my project looks like. 这就是我项目中文件的外观。

在此处输入图片说明

Thanks 谢谢

Especially on Windows, Java can be a lenient on the use of case within the file names. 尤其是在Windows上,Java可以宽松使用文件名中的大小写。 When running in Eclipse, the Pattern1.PNG is probably been picked up off the file system directly. 在Eclipse中运行时, Pattern1.PNG可能是直接从文件系统中拾取的。

Once embedded within the Jar however, the case matching becomes EXACT. 一旦嵌入到Jar中,大小写匹配就变成了EXACT。 This is because the resource is simply added to a zip file and Java uses the Zip Entry information to find content. 这是因为资源只是添加到zip文件中,而Java使用Zip Entry信息来查找内容。

Make sure you naming is EXACT to avoid issues. 确保命名正确,以避免出现问题。 Try /Images/Pattern1.PNG instead of /Images/Pattern1.png 尝试使用/Images/Pattern1.PNG代替/Images/Pattern1.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM