在我的populateArrayEnemy方法中,我用20个对象填充数组,最后将它们全部打印出来。
但是在我的paint和update方法中,enemyShip.size返回0。
我哪里出错了?
更新: 我的主要方法如下。
public class ActionEnemyShip {
EnemyShip es;
public ArrayList<EnemyShip> enemyShip = new ArrayList<EnemyShip>();
// Updating coordinates method //////////////
public void populateArrayEnemy(MainClass mc){
int Min = 0, Max=800, result;
for (int i =0; i <=20; i++){
x = Min + (int)(Math.random() * ((Max - Min) + 1));
y = 0 + (int)(Math.random() * ((600 - 0) + 1));
EnemyShip es = new EnemyShip(x,y);
enemyShip.add(es);
}
System.out.println(enemyShip);
}
public void update(MainClass mc, Player p){
for (int i = 0; i < enemyShip.size(); i++ ) {
EnemyShip es = new EnemyShip();
es = enemyShip.get(i);
es.setX(es.getX()+ENEMY_SHIP_SPEED);
enemyShip.set(i, es);
}
}
// Paint method //////////////////////
public void paint(Graphics g, MainClass mc) {
url = mc.getDocumentBase();
enemyShipImg = mc.getImage(url, "craft.png");
System.out.println(" paint "+enemyShip.size());
for (int i = 0; i < this.enemyShip.size(); i++){
EnemyShip es = new EnemyShip();
es = this.enemyShip.get(i);
g.drawImage(enemyShipImg, es.getX(), es.getY(), mc);
}
这是我的主要方法
public void init()
{
setSize(800, 600);
es = new EnemyShip();
as = new ActionEnemyShip();
//as.populateArrayEnemy(mc);
}
public void start() {thread.start();}
public void destroy() {running = false;}
public void stop() {running = false;}
public void run()
{
while(running)
{
as.update(this, p);
}
public void paint(Graphics g){
as.paint(g, this);
}
答案 0 :(得分:2)
public void init()
{
setSize(800, 600);
es = new EnemyShip();
as = new ActionEnemyShip();
//as.populateArrayEnemy(mc); <== this is not happening
}
一般来说,这段代码写的很差,你应该考虑重构它。您的错误似乎是as.populateArrayEnemy(..)
未被调用,因为它被注释掉了。