Once exported, java cannot find/draw images

浪尽此生 提交于 2019-11-28 02:12:52

Your code was initially looking for image files, and files do not exist inside of a Jar file, just resources. So you were correct to try using getClass.getResource("/res/client/BannerHeader.jpg");. But make sure that the image is in fact in the jar file in a directory off of the class file directory, and use a path that is relative to the class path directory.

The error isn't telling you that this is wrong or that the file is null, but rather you need to place this in a try/catch block. I suggest that you read the Exceptions Tutorial for more on this.

Edit 1
When you stated you had an uncaught exception error, it seemed to me that you had a compilation error, not a run-time exception. Sorry for the confusion.

As for where to place the images, it somewhat depends on what IDE you're using. I use Eclipse, and I add a directory off of my java file package directory that I call images and place my images there. I then use resources to look for "images/MyImage.jpg".

For example, say my packages in Eclipse look like so:

So the class files are located in the myPackage package, and the image file, GridBoxClassPic.JPG is located in the images directory off of the class file directory, so I can find it using the String String RESOURCE_PATH = "images/GridBoxClassPic.JPG";.

This code could show the image:

import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class MyClass {
   private static final String RESOURCE_PATH = "images/GridBoxClassPic.JPG";

   public MyClass() {
      try {
         BufferedImage image = ImageIO.read(getClass().getResource(RESOURCE_PATH));
         ImageIcon icon = new ImageIcon(image);
         JLabel label = new JLabel(icon);
         JOptionPane.showMessageDialog(null, label);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

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

well, if you followed method one, I think you need to just create the runnable jar file in eclipse. Then you need to put the images you are loading in the same directory as the jar file, having the same relative path you had mentioned in your program. For example

 your_directory
             ---> game_runnable.jar
             ---> res
                  ---> client 
                       -->BannerHeader.png

I think it will work then.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!