从其他类访问ArrayList

时间:2014-07-04 15:40:16

标签: java arraylist nullpointerexception applet

嗯......我错过了什么吗? 尝试从ArrayList中绘制导弹对象,但在调用p.missilies.size()时不断收到错误NullPointerException。导弹肯定在那里,并在Player类中实例化,但我如何从ActionMissile.class访问它?

ActionMissile类

public class ActionMissile {

public ArrayList<Missilies> missilies = new ArrayList<Missilies>();

 public void paint(Graphics g, MainClass mc) {
     url = mc.getDocumentBase();
     missile = mc.getImage(url, "missile.png");
     //missilies = p.getMissilies();
        for (int i = 0; i < p.missilies.size(); i++ ) {
            Missilies m = new Missilies(mc);
            m = (Missilies) p.missilies.get(i);
            g.drawImage(missile, x, y, mc);
        }       
    }

主要课程

ActionMissile a;

public void init()
{
    setSize(800, 600);
    p = new Player(this);
    e = new Enemy(this);
    m = new Missilies(this);
    a = new ActionMissile();

 public void paint(Graphics g){
    p.paint(g, this);
    e.paint(g, this);
    if (!p.missilies.isEmpty())
        a.paint(g, this);       
}

玩家类

  @Override
public void keyPressed(KeyEvent e) {
    switch (e.getKeyCode()){
    case KeyEvent.VK_SPACE:{

        if (lastKey == null || lastKey != e.getKeyChar()) {
            lastKey = e.getKeyChar();
            Missilies m = new Missilies(x,y);
            m.fire();
            missilies.add(m);
           System.out.println("Missilies "+missilies);            

1 个答案:

答案 0 :(得分:0)

更改:

p.missilies.size()

要:

mc.p.missiles.size()

你想检查mc中的导弹。

这看起来像,因为你在以下方法中调用方法:

if (!p.missilies.isEmpty())
    a.paint(g, this);     

该代码在mc中。因此该代码中的p也属于mc。