66

I am having a error for my GUI. Trying to set title bar icon then be included in a Runnable JAR.

BufferedImage image = null;
try {
    image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
} 
catch (IOException e) {
    e.printStackTrace();
}

frame.setIconImage(image);

Here is the error I am getting:

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at GUI.<init>(GUI.java:39)
    at GUI.main(GUI.java:351)

The image is in the correct directory which "resources" folder is the root of the project file

Pshemo
  • 122,468
  • 25
  • 185
  • 269
exlux15
  • 909
  • 1
  • 9
  • 16

3 Answers3

96

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:

For NetBeans:

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

    getClass().getResource("/resources/images/myImage.imageExtension");

  • 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 :

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");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new MyPanel();

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private class MyPanel extends JPanel {

        private BufferedImage image;

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

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, this);
        }
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new ImageExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}
Community
  • 1
  • 1
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • @trashgod : Thankx for the edit, but Better it will be, if you add your edit on top of mine, since the Java Doc explained that in a much better way than, what I did in my answer, it seems like :-) – nIcE cOw Apr 26 '12 at 17:21
  • @nIcEcOw: Honestly, I think your ASCII art is more legible. :-) – trashgod Apr 26 '12 at 21:18
  • 1
    @nIcEcOw This answer was considered worthy of mention in the [info. page](http://stackoverflow.com/tags/embedded-resource/info) for [tag:embedded-resource]. :) – Andrew Thompson May 10 '13 at 02:33
  • 1
    @AndrewThompson : Happy to know, that my answer, is providing the knowledge :-) Thankyou. It's a wonderful feeling, to know, that the answer is liked by many :-) Will try to provide more answers with the same valuable inputs, as I did with this answer. Thankyou again and KEEP SMILING :-) – nIcE cOw May 10 '13 at 15:16
11

There's a much easier way to load and set an image as a frame icon:

frame.setIconImage(
    new ImageIcon(getClass().getResource("/resources/icon.gif")).getImage());

And thats all :)! You don't even have to use a try-catch block because ImageIcon does not throw any declared exceptions. And due to getClass().getResource(), it works both from file system and from a jar depending how you run your application.

If you need to check whether the image is available, you can check if the URL returned by getResource() is null:

URL url = getClass().getResource("/resources/icon.gif");
if (url == null)
    System.out.println( "Could not find image!" );
else
    frame.setIconImage(new ImageIcon(url).getImage());
icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    wrong... it throws null pointer exception if the image wasn't there – Lasitha Lakmal Oct 29 '19 at 03:24
  • @LasithaLakmal What's wrong? Nobody said otherwise. If you need to handle "missing" images, the answer tells to check if `Class.getResource()` returns `null`. – icza Oct 29 '19 at 09:47
  • +1 because ImageIcon will work like a charm in conjunction with bufferedImage ( because they are siblings ) – clockw0rk Sep 02 '20 at 00:23
7

The image files must be in the directory resources/ in your JAR, as shown in How to Use Icons and this example for the directory named images/.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045