Loading resources like images while running project distributed as JAR archive

First of all, change this line :

image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));

to this :

image = ImageIO.read(getClass().getResource("/resources/icon.gif"));

More info, on as to where lies the difference between the two approaches, can be found on this thread – Different ways of loading a Resource

For Eclipse:

  • How to add Images to your Resource Folder in the Project

For NetBeans:

  • Handling Images in a Java GUI Application
  • How to add Images to the Project

For IntelliJ IDEA:

  • Right-Click the src Folder of the Project. Select New -> Package
  • Under New Package Dialog, type name of the package, say resources. Click OK
  • Right Click resources package. Select New -> Package
  • Under New Package Dialog, type name of the package, say images. Click OK
  • Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
  • Use the last link to check how to access this file now in Java code. Though for this example, one would be using


  • Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.

If you are doing it manually :

  • How to add Images to your Project
  • How to Use Icons
  • A Little extra clarification, as given in this answer’s first
    code example.

QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):

package swingtest;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

 * Created with IntelliJ IDEA.
 * User: Gagandeep Bali
 * Date: 7/1/14
 * Time: 9:44 AM
 * To change this template use File | Settings | File Templates.
public class ImageExample {

    private MyPanel contentPane;

    private void displayGUI() {
        JFrame frame = new JFrame("Image Example");

        contentPane = new MyPanel();


    private class MyPanel extends JPanel {

        private BufferedImage image;

        public MyPanel() {
            try {
                image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
            } catch (IOException ioe) {

        public Dimension getPreferredSize() {
            return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());

        protected void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, this);

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            public void run() {
                new ImageExample().displayGUI();

Leave a Comment