My jar file does not load images

I am currently writing a program that I need to send to a friend as a bank. The program has images that need to be downloaded for the program to work correctly, and I want all this to be contained in one bank. Currently it does not work with an executable bank or when I launch it through the command line. However, he works at netbeans.

Here is the code I'm using:

To upload the image I use:

protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getClassLoader().getResource(path); if (imgURL != null) { return new ImageIcon(Toolkit.getDefaultToolkit() .getImage(imgURL),description); } else { System.err.println("Couldn't find file: " + path); return null; } } 

for the url that I also tried just

  getClass().getResource(path) 

The line in which the image should be created is:

 this.img =createImageIcon(File.separator+"."+File.separator +"resources"+File.separator+"tiles"+File.separator+"tile.png","tile"); 

My jar file is installed with a folder containing class files and a resource folder, as at the top level.

I was looking for ways to solve this problem, but I can not find anything that works.

Thanks.

+1
source share
3 answers

Your URL will be evaluated as "/./resources/tiles/tile.png" , which makes no sense (but maybe the ClassLoader that is used when starting from NetBeans makes an error.)
Try to remove the initial "/./" . Also, you do not need links to File.separator , since the string is treated as a relative URL, and the forward slash is always valid.

+2
source

Instead of /./resources/back_img.png use resources/back_img.png with ClassLoader .
Here is an example:

  String path = "resources/back_img.png"; ClassLoader cl = ImageHandler.class.getClassLoader(); URL imgURL = cl.getResource(path); //URL imgURL = ImageHandler.class.getResource(path); if (imgURL != null) { ImageIcon icon = new ImageIcon(imgURL, description); Image img = icon.getImage(); Image sizedImg = img.getScaledInstance(width, height, Image.SCALE_DEFAULT); return new ImageIcon(sizedImg); } else { System.err.println("Couldn't find file: " + path); return null; } 
+1
source

Despite everything else, your code has the unenviable property of being slow.

Try something like

 URL x = get class.getclassloader.getresource(...) If x == null Throw new defect "expected ... But it wasn't there" 

Sorry for the formatting, but the iPad makes it too complicated to do it right.

0
source

Source: https://habr.com/ru/post/1338536/


All Articles