【问题标题】:All objects in arraylist have the same value [duplicate]arraylist 中的所有对象都具有相同的值[重复]
【发布时间】:2013-04-03 20:59:48
【问题描述】:

我想要做的就是创建一个简单的 Java 程序,它有一个充满对象的数组列表,在本例中是弹跳球,可以添加到游戏中。我希望它工作的方式是,你启动程序,它是一个空白屏幕。你按下空间,它会产生一个从侧面反弹的球,通过按下空间它会产生更多的球。我遇到的问题是当我添加更多球时,它会将数组列表中的每个项目设置为相同的 x 和 y 坐标。我正在使用 slick2D 库,但我认为这不是问题。

这是程序的主要部分

public static ArrayList<EntityBall> ballList;

    @Override
    public void init(GameContainer gc) throws SlickException {
        ballList = new ArrayList<EntityBall>();
    }

    @Override
    public void update(GameContainer gc, int delta) throws SlickException {
        String TITLE = _title + " | " + gc.getFPS() + " FPS" + " | " + ballList.size() + " entities";
        frame.setTitle(TITLE);

        Input input = gc.getInput();

        if (input.isKeyPressed(Input.KEY_SPACE)) {
            addBall();
        }
    }

    public void render(GameContainer gc, Graphics g) throws SlickException {
        for(EntityBall e : ballList) {
            e.render(g);
        }
    }

    public static void addBall() {
        ballList.add(new EntityBall(getRandom(0, _width - ballWidth), getRandom(0, _height - ballWidth), 20, 20));
    }

    public static int getRandom(int min, int max) {
        return min + (int) (Math.random() * ((max - min) + 1));
    }

这里是 EntityBall 类

package me.Ephyxia.Balls;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;

public class EntityBall {

    public static int x;
    public static int y;
    public static int height;
    public static int width;
    
    public EntityBall(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public void render(Graphics g){
        g.fillOval(x, y, width, height);
    }
}

【问题讨论】:

  • 如果您认为 rgettman 的回答很好,您可以接受。 (点击复选标记)

标签: java arraylist entity slick2d


【解决方案1】:

出现问题是因为EntityBall 中的实例变量xy 等是static,这意味着整个类中每个变量只有一个值。每次创建新实例时,这些值都会被覆盖。从EntityBall 中的字段声明中删除static,以便创建的每个球都有不同的值。

【讨论】:

  • 它成功了,谢谢我几乎崩溃并创建了一个数组并分别创建了 55 个对象。