每次我尝试引用我在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);
}
答案 0 :(得分:0)
您在start方法中将其声明为局部变量。
此: 抽屉抽屉=新抽屉(); 应该只是: drawer = new Drawer();