How can I find the java.net.URL for an image needed for ImageIcon?

Viewed 149

I'm trying to add an ImageIcon to a JLabel I'm adding to a JPanel to get Graphics for my Java Swing game. However, I can't seem to even create the ImageIcon for the JLabel with my current code. I've already tried looking through Stack Overflow, but I couldn't find an answer that fit my issue. pls help

protected ImageIcon createImageIcon(Class c, String file) {
        File f = new File(file);
        String path = f.getAbsolutePath();
        
        java.net.URL imgURL = c.getResource(path);
        
        System.out.println(imgURL);
        System.out.println(path);
        
        if (path != null) {
            return new ImageIcon(path);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

Called from:

Graphic startScreenG = new Graphic();
        Icon startScreenI = startScreenG.createImageIcon(MyAppClass, "download.jpg");
        JLabel startScreen = new JLabel(startScreenI);
        Screen.add(startScreen);

This returns:

null

C:\Users*justmyname*\Documents\NetBeansProjects\IA\download.jpg

1 Answers

Note that getResource works by name not file path. So for the c.getResource(path) to work as you intent, "download.jpg" file would need to be in the classpath IIRC. But since you already have a File object that represents the image file that you need, you could simply call f.toURI().toURL() Note that f.toURL() is deprecated.

Hope it helps!

Related