My jar file won't load images

前端 未结 3 361
后悔当初
后悔当初 2021-01-25 16:03

I am currently writing a program that I need to send to a friend as a jar. The program has images that need to be loaded for the program to work properly and I want it all to be

相关标签:
3条回答
  • 2021-01-25 16:37

    Instead of using /./resources/back_img.png, use resources/back_img.png with ClassLoader.
    Here is 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;
        }
    
    0 讨论(0)
  • 2021-01-25 16:41

    Your URL will evaluate to "/./resources/tiles/tile.png" which does not make sense (but maybe the ClassLoader that is used when you run from NetBeans tolerates the error.)
    Try dropping the initial "/./". Also you do not need the references to File.separator as the string is treated as a relative URL and the forward slash is always valid.

    0 讨论(0)
  • 2021-01-25 16:48

    Despite anything else your code has the unenviable property of being fail-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 hard to do it right.

    0 讨论(0)
提交回复
热议问题