<List> add question

I am trying to add a ‘ball’ entity with my mouse coordinates within my mouse class, however whenever I try to make a non-static reference in order to ‘add’ the ball it won’t increase the entity size (not adding on the screen).

Mouse.java:

public void mousePressed(MouseEvent e) {
	s.addEntity(new Ball(e.getX(), e.getY(), 15, 15));
}

Ball.java:


import java.awt.Color;
import java.awt.Graphics;


public class Ball extends Entity{
	private int x, y, width, height;
	private boolean removed;
	
	public Ball(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){
		if(!removed){
			g.setColor(Color.WHITE);
			g.drawRect(x, y, width, height);
		}
	}
	
	public void remove(){
		removed = true;
	}
	
}

Screen:


import java.awt.Color;
import java.awt.Graphics;
import java.util.*;

public class Screen {
	public List<Entity> entities = new ArrayList<Entity>();
	
	public void render(Graphics g){
		System.out.println(entities.size());
		for(int i = 0; i < entities.size(); i++){
			entities.get(i).render(g);
		}
	}
	
	public void addEntity(Entity e){
		System.out.println("ADDED" + e);
		entities.add(e);
	}

}

Making entities static works, but there must be another way around this?

How is Screen.render being called? Are you using active or passive drawing on your component? If it is passive then you have to call repaint() on your root container.

If it works when entities is static but doesn’t work anymore when it’s not static then you must have more then one Screen object and you add the entity to the wrong one.

Where do you set removed to false? That could be the problem.

DrZoidberg is right, if making “entities” non-static makes it not work, then you are creating multiple objects of type Screen and using different ones to add and draw.

Active (I didn’t want to post the screen code because it shouldn’t matter whether or not it appears but whether or not the entities.size increases)

On definition removed is false, but it doesn’t matter since I only want to see an increase in entities.size.

I don’t know what you mean by that

So…were there multiple Screen objects? Care to show us your main class that uses this Screen object?

edit: I was creating a new instance of an object of the same type, so in passing the same object (without referencing another one) it’ll add/render the entity properly

thx OP

Are you using a different Screen object in Mouse than Game? :wink: