Tino APCS

Accessing Resources Correctly

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:

  1. Right-click on your project in the package explorer and select new -> package.

  2. Name the package something like "resources" (please don't include the quotes in the name).

  3. Drag all your resource files such as images and sounds into the resources package.
    Note: Please select copy files, NOT link to files.

  4. 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();
          

Playing sound

  1. Here is a demo that shows how to play sounds.
  2. To use the MediaPlayer and Media classes, you'll need to update your VM arguments of your main class' Runtime Configuration to include javafx.media.

Dark Mode

Outline