0

In my game I have the following code:

   public Main() {
                p = new Potato();
                addKeyListener(new AL());
                setFocusable(true);
                ImageIcon i = new ImageIcon("C:/test.png");
                img = i.getImage();
                time = new Timer(5, this);
                time.start();
                en = new Enemy(700, 200, "C:/enemy.png");
                en2 = new Enemy(700, 200, "C:/enemy.png");
        }

However I would like to put test.png inside of the package, but when I do it creates errors with the i piece. I want to put the images inside of a folder inside the jar file, but then what would I put in there place? I'm mainly asking how do I make ImageIcons reference files inside of the jar.

Redux
  • 25
  • 4

2 Answers2

0

You will have to give a path relative to your class file location.

Read more on using relative paths :

Java- relative path of text file in main?

relative path in Java

How to define a relative path in java

Community
  • 1
  • 1
Adarsh
  • 3,613
  • 2
  • 21
  • 37
0

ImageIcon(String) expects a a File reference. When you embedded you resources into the application context (and them it the Jar), they can no longer be accessed liked files, instead, y need to use something like getClass().getResource(...)

For example, assuming that the image is in the same package as the class, you could use...

ImageIcon i = new ImageIcon(getClass().getResource("test.png"));

Or if the image is in another package, you might need to use

ImageIcon i = new ImageIcon(getClass().getResource("/path/to /resource/test.png"));
hveiga
  • 6,725
  • 7
  • 54
  • 78
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366