1

我在从另一个班级获取图像时遇到了一些问题。我以前从未遇到过这个问题。有人可以指出我正确的方向。

package main;

import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class Main extends JFrame {

    public static Character character;

    static GraphicsEnvironment graphicsEnvironment;
    static GraphicsDevice graphicsDevice;
    static DisplayMode displayMode;

    private Image i;

    public static void main(String[] args) {
        displayMode = new DisplayMode(1280, 720, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
        graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();

        Main m = new Main();
        m.run();
    }

    public void run() {
        setUndecorated(true);
        setResizable(false);

        graphicsDevice.setFullScreenWindow(this);

        try {
            graphicsDevice.setDisplayMode(displayMode);
        } catch (Exception e) {
        }
    }

    public void paint(Graphics g) {
        g.setColor(Color.cyan);
        g.fillRect(0, 0, displayMode.getWidth(), displayMode.getHeight());
        i = character.getImage();
        g.drawImage(i, 100, 100, this);
    }
}

package main;

import java.awt.Image;
import javax.swing.ImageIcon;

public class Character {
    private Image i;

    public Image getImage() {
        i = new ImageIcon(this.getClass().getResource("/raw/images/player1.png")).getImage();
        return i;
    }
}

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Main.paint(Main.java:52)

它说错误是i = character.getImage();

我在制作小程序时已经做过很多次了,如果我第一次尝试全屏游戏的话

4

2 回答 2

4

Remember to think about what the compiler is telling you.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

A NullPointerException means a reference variable hasn't been initialized (or is == null, for that matter). In your case, that means to debug it you'll have to check both i and character. If it was the image you were trying to return, the stacktrace would go one deeper.

Since you are initializing i, look back up at character. You never set character to anything, which means you can't use it in any declarations.

So, your solution is to do character = new Character(); in run() or main(String[] args), or you can set getImage() to static, and say i = Character.getImage();.

于 2013-08-07T03:44:15.713 回答
2
  1. 将方法声明改为public static Image getImage(){/*你的代码在这里*/}
  2. 调用该方法的语句确保第一个字母是大写的 C 而不是 c。如 Character.getImage()
于 2013-08-07T03:48:04.413 回答