【问题标题】:Export resource in jar file将资源导出到 jar 文件中
【发布时间】:2015-12-24 16:31:49
【问题描述】:

我在将带有后台资源的 Jframe 应用程序导出到 jar 文件中时遇到问题(没有任何外部资源文件夹。我更喜欢将所有内容都放入 jar 文件中以提高可移植性)。 这是代码。在 Eclipse 上一切正常,但是当我导出到 jar 文件时,应用程序不会加载,因为找不到资源“cccc.jpg”。 我已经尝试过 getResource() 但效果不佳。

// Load Background image
BufferedImage img = null;
try {
    img = ImageIO.read(new File("cccc.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

// Set Background image
Image dimg = img.getScaledInstance(640, 480, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));

【问题讨论】:

  • getResource 是正确的方法 - “效果不佳”是什么意思?
  • 肯定是路径问题。你把你的jpg放在好目录下?

标签: java eclipse background resources


【解决方案1】:

说您的代码在 ecplise 中工作是暗示您在项目文件夹的根目录中找到了“cccc.jpg”文件(这是您在 eclipse 中运行应用程序或单元测试时的当前文件夹)。

为了将文件作为资源打包到您的 jar 中:只需将其放入源文件夹的某个位置即可。如果您的源包名为“my.app.main”,则可以将图像文件直接放在“my”文件夹旁边并通过以下方式加载:

InputStream is = ClassLoader.getSystemResourceAsStream( "cccc.jpg" )

或将其放入子包(例如“my.app.images”)并通过以下方式加载:

InputStream is = ClassLoader.getSystemResourceAsStream( "my/app/images/cccc.jpg" )

顺便说一句:ImageIO.read 也可以将 InputStream 作为参数。

【讨论】:

    【解决方案2】:

    喜欢

    BufferedImage bufferedImage = ImageIO.read(MyClass.class.getResource("/images/cccc.jpg"));
    

    见:Loading image from a resource Can't read input file

    【讨论】:

      【解决方案3】:

      我解决了这个问题。现在,当我打开 jar 文件时,一切都已正确加载。

      Link to the picture of the problem solved

      【讨论】:

        猜你喜欢
        • 2013-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2011-10-26
        • 2019-09-03
        • 2014-02-03
        • 1970-01-01
        相关资源
        最近更新 更多