I just wrote a mini-program in java that takes an image and prints it on frame. I used JPanel to load the image:
public class Board extends JPanel {
private Image mummy;
public Board() {
initBoard();
}
private void initBoard() {
loadImage();
int w = mummy.getWidth(this);
int h = mummy.getHeight(this);
setPreferredSize(new Dimension(w, h));
}
private void loadImage() {
ImageIcon ii = new ImageIcon("mummy.png");
mummy = ii.getImage();
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(mummy, 0, 0, null);
}
}
and JFrame to print it. Then I created the .jar file via the export section of Eclipse (Runnable JAR file).
The problem is that now I can't load the image when I run the .jar file. I tried putting the image everywhere on the .jar zip but simply the code doesn't load it.
Everyone knows how to load the images using this method, or should I use a wrapper to create the .jar file instead of eclipse?
Guys I figured it out:
The ImageIcon(""), has as default starting directory where all the code is put, but varies between an eclipse project and an eclipse generated Runnable jar file. -When it's a project: it's the directory of the project, so where the src and bin directory are. -When it's a .jar: src doesn't exist, and the starting directory now is the directory where the .jar file is situated.
For example: for simplicity let's situate the created runnable files in the ~ directory.
-Using new ImageIcon("src/images/mummy.png")
, you'll have to put the directory "images" with the relative files in the src directory of the project, where the source files and packages are, making a structure like this:
...eclipse-workspace/Project/src/cli/*.java -where the source code is.
...eclipse-workspace/Project/src/images/mummy.png -where the file is.
After you created the runnable .jar with eclipse, you'll have to put a new "src" directory with the "images" in the same directory where the .jar is, making a structure like this:
~/project.jar (the .jar file)
~/src/images/mummy.png (the image I loaded in the code with new ImageIcon("src/images/mummy.png")
Thanks for the comments anyways.