Search code examples
javaswingiconsjframeimageicon

Problem in adding Icon to a JFrame


I have tried several methods to add an Icon to a JFrame. Every method work perfectly when I run it using the source code.

for example:

jframe.setIconImage(Toolkit.getDefaultToolkit().getImage("iconimages/icon.png"));

But none of them work when I run it using the jar file. I know the problem is with the path of the image file. How can I solve this?

Edit:

public Ui() { 
   initComponents(); 
   setLocationRelativeTo(null); 
   this.setIconImage(getImageIcon("icon.png").getImage());
} 

private ImageIcon getImageIcon(String fileName) {
   String imageDirectory = "iconimages/"; 
   imgURL = getClass().getResource(imageDirectory + fileName); 
   return new ImageIcon(imgURL); 
}

I tried this but now I get a null pointer exception.

--------------------------------------------------------------------------------

Edit [Solution] : I found the solution.

I added ../ to the path additionally and it works perfectly!!! :D

 ImageIcon imageIcon = new ImageIcon("../imageicons/icon.png");
 this.setIconImage(imageIcon.getImage());

Thanks all for try to help me. :)


Solution

  • You should use a URL. Like this:

     /**
      * Loads and returns an {@link Image} resource. 
      * @param fileName name of the image resource.
      * @return Image as resource.
      */
      public Image getResourceImage(String fileName) {
          String imageDirectory = "images/";
          URL imgURL = getClass().getResource(imageDirectory + fileName);
          Image image = null;
          try {
             image = ImageIO.read(imgURL);
           } catch (IOException e) {}
          return image;
        }