开发者

Java swing app can't find image

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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜