【问题标题】:How to get resources working in runnable jar?如何让资源在可运行的 jar 中工作?
【发布时间】:2014-02-07 04:43:59
【问题描述】:

我的 Jframe 中有一个图像图标。我在其中使用了一个图像。当我导出到可运行的 Jar 时。图像不显示。

String iPath = "res/images/Mobile.png";
JLayeredPane layeredPane = new JLayeredPane();
 layeredPane.setBounds(0, 0, 315, 610);
 InputStream stream = (InputStream) getClass().getResourceAsStream(iPath);
 JLabel mobileImageLabel;
 mobileImageLabel = new JLabel(new ImageIcon(iPath));

          //mobileImageLabel = new JLabel(new ImageIcon(ImageIO.read(stream)));
       // mobileImageLabel = new JLabel(new ImageIcon(AppFrame.class.getResource(iPath)));

                    mobileImageLabel.setBounds(0, 0, 315, 610);
                    mobileImageLabel.setVisible(true);
                    layeredPane.add(mobileImageLabel, Integer.valueOf(0));

我用谷歌搜索并找到了 getResourceAsStream 方法。但它似乎抛出了 NullPointerException。

所以请帮助我正确的方向:)

感谢您的帮助...

注意 我试过的方法被评论了

【问题讨论】:

  • 我也有同样的问题,最好在另一个系统上尝试 getResourceAsStream 方法。
  • 使用 zip 应用程序(例如 7-zip)打开您的 runnable.jar,并查看该文件是否包含在 jar 和相应的目录中。通常错误的设置会阻止资源被包含到 jar 中。
  • embedded-resource信息。

标签: java swing jframe getresource


【解决方案1】:

要在按钮中设置图像,我这样做了:

JButton yourButton = new JButton("text button");
        try {
            yourButton.setIcon(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png"))));
        } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }

您的项目中必须有这样的图像:

在你的情况下,我认为的答案是这样做:

new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png")))

【讨论】:

    【解决方案2】:

    尝试替换

    String iPath = "res/images/Mobile.png";
    

    String iPath = "C:/..../res/images/Mobile.png";
    

    每当您使用图像时,请尝试放置图像的完整路径。因此,当您生成 .jar 文件并尝试从不同的位置运行它时(可能您希望 jar 应该从桌面运行),您将获得所有图像。

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多