每次我尝试引用我在 pain 方法中创建的 Drawer 类时,它都会给出一个空指针异常。但是,在绘制函数之外,该类可以完美运行。我制作的游戏类也适用于paint方法。我不确定为什么我不能引用抽屉类。
public class Main extends Applet implements Runnable, KeyListener {
public static boolean CONSOLE = true;
// Integers
public final String Title = "";
public final int res_X = 800;
public final int res_Y = 600;
private Image image;
private Graphics second;
private URL base;
public Game game;
public Drawer drawer;
public void init() {
setSize(res_X, res_Y);
setBackground(Color.GRAY);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle(Title);
try {
base = getDocumentBase();
} catch (Exception e) {
e.printStackTrace();
}
}
public void start() {
**Drawer drawer = new Drawer();**
Thread mainThread = new Thread(this);
mainThread.start();
Thread gameThread = new Thread(game = new Game(drawer));
gameThread.start();
}
public void run() {
while (true)
repaint();
}
public void paint(Graphics g) {
**System.out.println((drawer == null)?"Null":"Exists");**
^ if I replace with game it returns Exists
g.fillRect(0, 0, res_X, 20);
g.fillRect(0, res_Y - 20, res_X, 20);
g.fillRect(0, 0, 20, res_Y);
g.fillRect(res_X - 20, 0, 20, res_Y);
g.fillRect(game.player.xPos, game.player.yPos, 20, 60);
}