-3

I am trying to change the icon of my Java application. Here is the structure of my project:

src
   gui
      FileCopyManager.java
images
    folder.png

Now I have the following code:

public class FileCopyManager extends JFrame{
    public void changeIcon() {
        this.setIconImage(new ImageIcon(Toolkit.getDefaultToolkit()
                .getClass().getResource("../../images/folder.png")).getImage());
    }
    public FileCopyManager() {
        changeIcon();
        this.setSize(800,600);
        this.setVisible(true);
    }
    public static void main() {
        new SwingUtilities.invokeLater(()->{
            new FileCopyManager();
        });
    }
}

However when I try to run this code I get a NullPointerException on the this.setIcon line.

Any ideas?

dur
  • 15,689
  • 25
  • 79
  • 125
cssGEEK
  • 994
  • 2
  • 15
  • 38
  • 1
    Split the line into more lines, by using intermediate variables and/or use a debugger. You should probably also make sure the resource exists before using it and throw an exception if it doesn't. – HopefullyHelpful Aug 20 '16 at 12:45
  • search for classloader.getresource in the SO search – HopefullyHelpful Aug 20 '16 at 12:57
  • getResource() probably returns null. the resource path is wrong. try "/images/folder.png" – gclaussn Aug 20 '16 at 12:58
  • 99% probability that `getResource("../../images/folder.png")` is returning `null` because the relative path is not relative to the place you think it is, or the file is not being deployed where you think it is, or the file just doesn't exist. – Jim Garrison Aug 20 '16 at 13:58

1 Answers1

-1

I would recommend to move your image folder to /src folder and use as :

src
 |---gui
 |  |-FileCopyManager.java
 |---images
    |-folder.png

use as :

public void changeIcon() {
    setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("images/folder.png")));
}

You can also create a method with get image from system and place it :

protected static Image createImage(String path, String description) {
    URL imageURL = Main.class.getResource(path);         
    if (imageURL == null) {
        System.err.println("Resource not found: " + path);
        return null;
    } else {
        return (new ImageIcon(imageURL, description)).getImage();
    }
}

In constructor use as :

setIconImage(createImage("/images/folder.png", "icon"));
Iamat8
  • 3,888
  • 9
  • 25
  • 35