关于Java:编译时出现图像问题

Problems with images when compiled

我一直在互联网上尝试弄清楚如何将图像图标编译到可运行的jar中后显示。我发现这个问题的方法为时已晚,我在eclipse上运行了我的程序很多次,并且一切正常,现在六个月后项目完成,我用eclipse编译了程序,没有音频或图像。在网上阅读,它说关于images文件夹的位置应该在jar中,但是我的文件夹没有放在那里吗?

我玩过images文件夹在源文件夹中移动它,但是没有用。我感觉这可能与资源的路径有关...但是那仅仅是猜测。

我建立了一个简单的程序,该程序具有相同的结果...在Eclipse中运行时有效,但在编译时不起作用。有人可以通过修改下面的代码向我展示一个示例。预先感谢。

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package ImageIcon;

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Gui {

public static JLabel c;

public Gui(){
    JFrame f = new JFrame();

    JPanel p = new JPanel();
    p.setBounds(0, 0, 120, 200);
    p.setBackground(Color.black);
    p.setLayout(null);

    JPanel bg = new JPanel(new BorderLayout());
    bg.setBounds(50, 50, 15, 15);
    bg.setBackground(Color.white);

    ImageIcon a = new ImageIcon("images/success.jpg");
    c = new JLabel(a);

    f.setSize(100, 200);
    f.setLayout(null);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

    f.add(p);
    p.add(bg);
    bg.add(c);
}

public static void main(String[] args) {
    new Gui();
}

}

enter


使用当前目录设置,images目录甚至都不会内置到jar中。尝试提取它,您很可能会发现它不在其中。

您可以通过以下事实看出来:文件夹中没有小package徽标,如resources

所示

enter

src是内置在类路径(/ jar)中的唯一默认目录。我们需要将resources放入src

enter

1
2
ImageIcon icon = new ImageIcon(
         getClass().getResource("/resources/stackoverflow.png"));
  • 第三张图片:

    1
    2
    ImageIcon icon = new ImageIcon(
             getClass().getResource("/stackoverflow.png"));
  • 要配置构建路径以使用第三个选项,请遵循此答案中示例2中的说明。


    从您的屏幕截图来看,该图像位于一个名为" \\ images "的文件夹中。将其放在类路径内的文件夹中:src / images / success.jpg并调用:

    1
    ImageIcon a = new ImageIcon(getClass().getResource("/images/success.jpg"));