Java Swing: Displaying images from within a Jar

后端 未结 5 1265
野趣味
野趣味 2020-11-22 15:13

When running a Java app from eclipse my ImageIcon shows up just fine.

But after creating a jar the path to the image obviously gets screwed up.

Is there a wa

5条回答
  •  感动是毒
    2020-11-22 16:11

    This is working for me to load and set the content pane background image:

    jar (or build path) contains:

     - com
     - img
     ---- bg.png
    

    java contains:

    JFrame f = new JFrame("Testing load resource from jar");
    try {
        BufferedImage bg = ImageIO.read(getClass().getResource("/img/bg.png"));
        f.setContentPane(new ImagePanel(bg));
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Tested and working in both jar and unjarred (is that the technical term) execution.

    BTW getClass().getClassLoader().getResourceAsStream("/img/bg.png") - which I tried first - returned me a null InputStream.

提交回复
热议问题