javaarraylistentityslick2d

All objects in arraylist have the same value


All I want to do is create a simple Java program that has an arraylist full of objects, in this case bouncing balls, that can be added to in game. The way I want it to work is, you start the program and it is a blank screen. You press space and it creates a ball that bounces off the sides, and by pressing space it makes more balls. The problem I have is when I add more balls, it sets every item in the arraylist to the same x and y coordinates. I'm using the slick2D library, but I don't think that's the problem.

Here is the main part of the program

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));
    }

And here is the EntityBall Class

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);
    }
}

Solution

  • The problem occurs because your instance variables x, y, etc. in EntityBall are static, meaning there is only one value of each for the entire class. Each time a new instance is created, the values are overwritten. Remove static from the field declarations in EntityBall, so that there are distinct values for each ball created.