0

I'm making a torpedo game for school in java with swing gui, please see the zipped source HERE.

I use custom button icons and mouse cursors of images stored in the /bin/resource/graphics/default folder's subfolders, where the root folder is the program's root folder (it will be the root in the final .jar as well I suppose) which apart from "bin" contains a "main" folder with all the classes. The relative path of the resources is stored in MapStruct.java's shipPath and mapPath variables. Now Battlefield.java's PutPanel class finds them all right and sets up its buttons' icons fine, but every other class fail to get their icons, e.g. Table.java's setCursor, which should set the mouse cursor for all its elements for the selected ship's image or Field.java's this.button.setIcon(icon); in the constructor, which should set the icon for the buttons of the "water".

I watched with debug what happens, and the images stay null after loading, though the paths seem to be correct. I've also tried to write a test file in the image folder but the method returns a filenotfound exception. I've tried to get the path of the class to see if it runs from the supposed place and it seems it does, so I really can't find the problem now.

Could anyone please help me? Thank you.

animuson
  • 53,861
  • 28
  • 137
  • 147
KáGé
  • 823
  • 2
  • 12
  • 23
  • Take a look at http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html to give you an idea on other ways to structure your file system and using getResource(). Also, before submitting your assignment, you should really comment your code. – NG. Apr 17 '10 at 13:46

2 Answers2

2

You need to load icons like this:

ClassLoader cl= this.getClass().getClassLoader();
URL imageURL   = cl.getResource("resources/...");
ImageIcon icon = new ImageIcon(imageURL);

And you need to add your resource folder to the classpath in Eclipse. Note that the path is not a file path, this way it will work if you decide to bundle your app in a jar file.

Guillaume
  • 14,306
  • 3
  • 43
  • 40
  • Thanks, and sorry for the lack of comments – KáGé Apr 17 '10 at 17:47
  • Looks like resources have to be placed inside the package structure only. So, if I place the images\a.png next to my Test.java file in Eclipse it works. – Teddy Jun 16 '14 at 09:56
0
btnRegistration.setIcon(createImageIcon("reg.png"));

protected ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = Master.class.getClassLoader().getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL);
    } else {
    System.out.println("Couldn't find file: " + path);
    return null;
    }
}

here btnRegistration is my JButton Master is my Class and reg.png is my image that is belong in my project

Mahfuz Ahmed
  • 721
  • 9
  • 23