简体   繁体   English

如何找到 ImageIcon 所需图像的 java.net.URL?

[英]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.我正在尝试将 ImageIcon 添加到 JLabel 我正在添加到 JPanel 以获取我的 Java Swing 游戏的图形。 However, I can't seem to even create the ImageIcon for the JLabel with my current code.但是,我似乎无法使用当前代码为 JLabel 创建 ImageIcon。 I've already tried looking through Stack Overflow, but I couldn't find an answer that fit my issue.我已经尝试查看 Stack Overflow,但找不到适合我的问题的答案。 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 C:\\Users*justmyname*\\Documents\\NetBeansProjects\\IA\\download.jpg

Note that getResource works by name not file path.请注意, getResource按名称而不是文件路径工作。 So for the c.getResource(path) to work as you intent, "download.jpg" file would need to be in the classpath IIRC.因此, c.getResource(path)按照您的意图工作,“download.jpg”文件需要位于类路径 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.但是由于您已经有一个代表您需要的图像文件的 File 对象,您可以简单地调用f.toURI().toURL()注意f.toURL()已被弃用。

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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