new ImageIcon("./image/risk.jpg")
The images don't appear in the jar file
Non sequitur. Whether the image file is in that jar or not is irrelevant; this does not work with jar files, period.
That ImageIcon constructor takes in a file argument. File, here, is to be taken literally: It refers to a path to a file on your actual disk. You go with .
, meaning: Current working directory, and thereby have lost all chances at a stable app; current working directory is whatever the JVM got started from and therefore unreliable. Even if you wave a magic wand and solve that problem, the next more pressing issue is that there is no risk.jpg file anywhere - it's an entry in a jar file, which is not, itself, a file. Merely an entry in a jar.
The solution
The solution is not to use that constructor, and instead to rely on java's resource retrieval system:
class MyClass {
public void foo() {
URL url = MyClass.class.getResource("risk.jpg");
}
}
This gets you a URL that represents a resource (could be an actual file, but could also be an entry on disk, the web, from a database, generated on the fly - whatever the classloader is providing. If you didn't mess with custom classloaders, it will always be either a file on disk, or entry in a jar file), and this can also be passed to ImageIcon
(it also has a constructor that takes a URL).
This then looks for a file named risk.jpg
which is sitting in the same place that MyClass.class
is sitting. Whether that is on disk someplace, or in a jar file (so if this is in package com.foo;
, you have a jar file with entry com/foo/MyClass.class
, and that command would then find the entry com/foo/risk.jpg
in the same jar file. You can use a prefix slash to go from the root of the jar: MyClass.class.getResource("/image/risk.jpg")
(note, no leading dot!) will look in that jar for entry image/risk.jpg
.
Great! Uh, but, that image should be in the jar, right?
Yes, this code will ensure you look in the same place class files are, which is good, but you still need to ensure the build is set up properly. 'let eclipse make a jar' is not a recommended build solution; invest some time in learning maven or gradle. However, if you insist, eclipse should just include them, but put the jpg in a source dir, right next to your java file (eclipse knows that non-java files are to be copied over, and java files are to be compiled).
In other words, if you insist on using eclipse's 'make a jar' as build tool, image
has to move into src
.
Alternatively, set up a basic maven project, where source is in src/main/java
and image files and the like are in src/main/resources
, use the maven plugin in eclipse to read the maven based project in, and that works too, if you want these directories fully separated for some reason.