使用其他本地包的图像时出现问题

Sha*_*wat 4 java swing jlabel

我在框架中有一个JLabel,当我点击不同的按钮时,我想要有不同的图像.实现这一点很容易.这是代码

    ImageIcon icon = new ImageIcon (img);
    icon.getImage().flush();
    shopBanner.setIcon(icon);
Run Code Online (Sandbox Code Playgroud)

问题i0,早些时候我提供了像C:\ Documents\xxx这样的图像的完整路径.现在,当我在其他计算机上尝试使用jar时,我发现没有使用图像,这很明显,因为分配的路径在其他计算机中不存在.

回到项目我有2个包,一个用于称为图像的图像,另一个用于称为smartshopping的源文件.我尝试使用几个代码,但无法从包"图像"调用图像.请帮我解决问题.如果我提供完整的路径为C:/ Docs,该项目在"我的"计算机上工作正常.

这是代码

    Image img = ImageIO.read(getClass().getResource("images/bb-banner-main.jpg"));
    ImageIcon icon = new ImageIcon (img);
    icon.getImage().flush();
    shopBanner.setIcon(icon);
Run Code Online (Sandbox Code Playgroud)

我甚至试过了

    URL img= this.getClass().getResource("images/icon.png");
    ImageIcon imageIcon = new ImageIcon(img);
    //icon.getImage().flush();
    shopBanner.setIcon(imageIcon);
Run Code Online (Sandbox Code Playgroud)

到目前为止没有任何工作.我究竟做错了什么.图像包被命名为图像.

JB *_*zet 8

Foo.class.getResource("images/icon.png")认为images/icon.png是相对的路径Foo.class.因此,如果Foo是在包中com.bar,它将寻找com/bar/images/icon.png.

在路径的开头加上斜杠使其成为绝对值(即从类路径的根开始).

顺便说一句,你让它变得不必要的复杂.无需使用ImageIO读取图像或刷新图像.做就是了

ImageIcon icon = new ImageIcon(Foo.class.getResource("/images/icon.png"));
Run Code Online (Sandbox Code Playgroud)

注意:我更喜欢硬编码Foo.class而不是使用getClass(),因为getClass()如果它被子类调用将返回另一个类,因此相对路径将指向另一个位置,大多数时候,它不是所需的位置.