Home » Java » java – Storing randomized Sprites in an ArrayList yield the same x/y coordinates-Exceptionshub

java – Storing randomized Sprites in an ArrayList yield the same x/y coordinates-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Say we have an ArrayList meant for storing objects:

public List<Sprites> nodes = new ArrayList<Sprites>();

We then want create some objects (in this case rectangular shapes) using a for-loop, store them in the ArrayList and also display them randomly on the stage, so we also randomize the x and y coordinates.

    for (int i = 0; i<3; i++) {

            double rnx =   Math.random() * 500+1;
            double rny =  Math.random() * 500 +1;           

            Sprite object = new Sprite((int) rnx,(int)rny,40,40,"object1",Color.BROWN);

            nodes.add(object);
            root.getChildren().add(object);
            System.out.println(nodes);

However, if we then want to print the Arraylist on the console, we get the following output:

[Rectangle[x=0.0, y=0.0, width=40.0, height=40.0, fill=0xa52a2aff], Rectangle[x=0.0, y=0.0, width=40.0, height=40.0, fill=0xa52a2aff], Rectangle[x=0.0, y=0.0, width=40.0, height=40.0, fill=0xa52a2aff]]

As we can see, the objects in the Arraylist all have the same x and y coordinates and they are all set to 0.
on the stage however, the objects do indeed appear randomly.

What is the problem here?
Am I missing something incredibly obvious here or using a wrong type of List perhaps?

Edit1:

root.getChildren().add(object);

adds the object on the stage.

Here is the Constructor for Sprites:

public class Sprites extends Rectangle {
public double width, height;        


    final String type;

    public Sprites(int x, int y, int w, int h, String type, Color colour){
        super(w, h,colour);
        this.type = type;
        this.width=w;
        this.height=h;

        setTranslateX(x);
        setTranslateY(y);
    }

There is no specific toString() method, I just used the built-in feature of ArrayLists as can be seen here: https://www.w3schools.com/java/showjava.asp?filename=demo_arraylist_add

Edit2: Debugging has shown that the properties of the objects are all set to 0. This is also applicable for manually generated objects.

How to&Answers:

Listing is not full.
I advise you to check toString method and constructor of Sprite (Rectangle?)