【问题标题】:I cant reference a class inside of paint(graphics g)我不能在paint中引用一个类(图形g)
【发布时间】:2013-04-28 01:56:54
【问题描述】:

每次我尝试引用我在 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);

}

【问题讨论】:

    标签: java applet null awt paint


    【解决方案1】:

    您在 start 方法中将其声明为局部变量。

    这个: 抽屉抽屉 = new Drawer(); 应该只是: 抽屉 = 新抽屉();

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2022-01-02
      • 1970-01-01
      • 2020-12-01
      • 2013-11-29
      相关资源
      最近更新 更多