-2

我最初是从 Chillax 开始的,在临近截止日期遇到了这么多问题之后,我回到了我更熟悉的 IDE,NetBeans,我改变了我的方法,制作了一个更基本的“Asteroid”类游戏:

在 NetBeans 中,我得到:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at gayme.Craft.<init>(Craft.java:27)
at gayme.Board.<init>(Board.java:54)
at gayme.Gayme.<init>(Gayme.java:9)
at gayme.Gayme.main(Gayme.java:19)
Java Result: 1

资料来源:(工艺 26 - 34)

    public Craft() {
    ImageIcon ii = new ImageIcon(this.getClass().getResource("craft.png"));
    image = ii.getImage();
    width = image.getWidth(null);
    height = image.getHeight(null);
    missiles = new ArrayList();
    visible = true;
    x = 40;
    y = 60;}

(板 54)

    craft = new Craft();

(同性恋 9)

    add(new Board());

(盖米 19)

   new Gayme();

我有一些我真正需要解决的问题,而我睡眠不足的大脑在每一个问题上都出现了损失。随时为您喜欢的任何游戏提供帮助。非常感谢你们!

4

1 回答 1

5

有3种方法:

关于使用位于其中的 Jar 文件和资源需要记住的一些事项:

  • JVM 区分大小写,因此文件和包名区分大小写。即主类位于mypackage我们现在无法使用如下路径提取它:myPackAge

  • 任何句号 '.' 位于包名中的应替换为“/”

  • 如果名称以“/”开头(“\u002f”),则资源的绝对名称是名称中“/”后面的部分。资源名称在执行类时以/开头,并且资源位于不同的包中。

让我们使用我首选的方法进行测试,getResource(..)该方法将返回我们资源的 URL:

我创建了一个包含 2 个包的项目:org.testmy.resources

在此处输入图像描述

如您所见,我的图像在my.resources中,而 Main 类main(..)org.test中。

主.java:

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Main {

    public static final String RES_PATH = "/my/resources";//as you can see we add / to the begining of the name and replace all periods with /
    public static final String FILENAME = "Test.jpg";//the case sensitive file name

    /*
     * This is our method which will use getResource to extarct a BufferedImage
     */
    public BufferedImage extractImageWithResource(String name) throws Exception {

        BufferedImage img = ImageIO.read(this.getClass().getResource(name));

        if (img == null) {
            throw new Exception("Input==null");
        } else {
            return img;
        }
    }

    public static void main(String[] args) {
        try {
            BufferedImage img = new Main().extractImageWithResource(RES_PATH + "/" + FILENAME);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

如果您使用的名称RES_PATHFILENAME没有对实际文件进行适当的更改,您将得到一个异常(只是向您展示我们必须对路径有多小心)

更新:

对于您的具体问题,您有:

ImageIcon ii = new ImageIcon(this.getClass().getResource("craft.png"));

它应该是:

ImageIcon ii = new ImageIcon(this.getClass().getResource("/resources/craft.png"));

Alien其他类也需要更改。

于 2012-12-10T08:04:28.977 回答