When referencing resources in a Java project, as for example photos, sound clips, video, etc., it is important to do it correctly because otherwise we may find errors when executing the application out of the IDE from a JAR file or on a different operating systems.
The method getResource() of each class allows to retrieve a file taking as a reference the path where this class is located. Example: MyClass.getResource(“file.ext”);
In order to export code more easily, instead of writing each time the class name (MyClass…) depending of the file, some developers use the method this.getClass(), that returns always the current class.
BufferedImage bImage = ImageIO.read(this.getClass().getResource("icon.png");
Example to retrieve an image for an ImageIcon:
ImageIcon image = new ImageIcon(this.getClass().getResource("/package/sub_package/image_name.png"));
- “Loading resources like images while running project distributed as JAR archive“; stackoverfliow
- “Referencing an image in a JAR file“; stackoverflow
- “this.getClass().getResource(“”).getPath() returns an incorrect path“; stackoverflow