If your GUI needs to access images, sound files, or other data, you will eventually run into problems if you are accessing your resources incorrectly (i.e. hardcoding paths). The following pattern is recommended for accessing resources:
Right-click on your project in the package explorer and select new -> package.
Name the package something like "resources" (please don't include the quotes in the name).
Drag all your resource files such as images and sounds into the resources package.
Note: Please select copy files, NOT link to files.
Follow the examples below to access your resources.
To access an image named "fireBall.png" located in the "resources" package:
String path = getClass().getClassLoader().getResource("resources/fireBall.png").toString();
To access a file from a static context from class named MyClass, write:
String path = MyClass.class.getClassLoader().getResource("resources/fireBall.png").toString();
If you need an InputStream (to read a text file with a Scanner for example):
InputStream stream = getClass().getClassLoader().getResourceAsStream("resources/data.txt");
If you need a URI:
String uri = getClass().getClassLoader().getResource("resources/song.mp3").toURI().toString();
Create an Image from a file named "fireBall.png" located in the "resources" package:
Image img = new Image("resources/fireBall.png");
javafx.media.Last modified: March 03, 2026
Back to Misc Things To Know