java - 从返回 null 的源文件夹加载图像

标签 java swing file-io null embedded-resource

您好,我在从我的资源文件夹导入图像时遇到问题。我已经在谷歌上看了遍(或者我认为),但我不知道我做错了什么。

感谢所有帮助,谢谢

这是我的java项目的图片:

Here is my picture

这是我的游戏代码:

public Game(){

    handler = new Handler();
    this.addKeyListener(new KeyInput(handler));

    new Window(WIDTH, HEIGHT, "Testing", this);

    BufferedImageLoader loader = new BufferedImageLoader();
    level = loader.loadImage("/level.png");

    hud = new HUD();
    spawn = new Spawn(handler, hud);
    r = new Random();
    walls = new WallsMap(handler);
    cam = new Camera(0, 0);

    walls.render();  
    handler.addObject(new Player(WIDTH/2-32, HEIGHT/2-32, ID.Player, handler));
}

最后是我的 BufferedImageLoader 类:

    public class BufferedImageLoader {

    private BufferedImage image;

    public BufferedImage loadImage(String path){
        try {
            image =  ImageIO.read(getClass().getClassLoader().getResourceAsStream(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}

最佳答案

要解决您的特定问题,这两个选项中的任何一个都应该起作用,以便可以正确定位资源:

  • 从 loadImage 方法中删除对 getClassLoader() 的调用,这样调用就只是 getClass().getResourceAsStream(path) - 或 -
  • "/level.png" 中删除斜杠,这样您对 loadImage 的调用看起来像 loader.loadImage("level.png")

不过,总的来说,我同意mastercork889 ,更好的做法是将您的资源也组织到包中。

编辑:

回应mastercork889的评论说我的答案应该是 AND 而不是 OR,我想我应该详细说明为什么它确实是异或。我本来会发表评论的,但我对堆栈溢出还太陌生,不允许发表评论,无论如何,这是相当多的信息:)

删除对 getClassLoader() 的调用是可行的,因为那时您正在使用 Class 类的 getResourceAsStream() 方法,它确实在委托(delegate)给 ClassLoader 类的 getResourceAsStream() 方法之前的额外工作。

来自 the Java API :

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

由于您的资源不在包中,并且位于源文件夹的顶层(看起来 res 是一个“Eclipse 源文件夹”),所以 级别。 png 斜杠后面的部分将以绝对方式充分标识资源的位置。

"/level.png" 中删除斜杠也有效,因为当对象的类加载器(应该是系统类加载器)查找资源时,它将尝试解析您的资源以绝对的方式。开头斜杠的特殊处理是 ClassgetResourceAsStream() 方法特有的行为,而不是 ClassLoader

AND 不起作用的原因是,如果您从 Class 调用 getResourceAsStream() 方法并删除斜杠,那么它将尝试定位资源在关联类所在的同一包中。如果您选择使用 AND 选项,那么您需要将 level.png 移动到 com.plat.gfx 包。

最后一点,我构建了一个小型测试程序,其格式与您的示例相同,一旦我遵循了两个建议之一,它就对我有用。

资源、类和类加载器的微妙之处可能非常棘手。祝你的项目好运!

关于java - 从返回 null 的源文件夹加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490750/

相关文章:

java - 如何在android studio中导入zebra包?

java - 制作 Java 面板全屏

python - "OSError: [Errno 22] Invalid argument"当读取大文件时

c - 将 FILE * 保存到 C 中的结构中

java - Spring boot - 设置全局错误处理程序以屏蔽 REST 端点

java - Maven 'deploy' 导致签名操作后代码重新打包(BAD签名)

java - 如何正确实现类继承,在java neo4j中注释为@QueryResult

java - JCombobox focusLost 没有触发 - 为什么会这样?

java - 对齐所有 gridbaglayout 元素

objective-c - UIWebView 不打开 ms word (doc) 和 ms excel (xls) 文件