简体   繁体   中英

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM