Yves Gonzaga
Yves Gonzaga

Reputation: 1048

Creating an object dynamically and add it to the list JavaFX

I want to create an object dynamicall for example a circle in JavaFX. My code will go like this.

 List<Node> list = new ArrayList<>();

    // Create circle dynamically
    for(int i = 0; i < 10; i++) {
        list.add(new Circle());
    }

My problem now is on how to add uniqueness of each circle. For example if I am going to add different color and size of each circle. How can I achieve it? Please help.

Upvotes: 0

Views: 1175

Answers (2)

Chexxor
Chexxor

Reputation: 416

RANDOM: It all comes down to how you wanna change them, if you want each circle to have random attributes, then make use of the Math.rand() method in combination with the circle methods/constructor, for example:

for(int i = 0; i < 10; i++){
    Circle circle = new Circle(Math.rand() * 600, Math.rand() * 400, Math.rand() * 30 + 20);
    list.add(circle);
    switch((int)(Math.rand() * 4)){
    case 0:
        circle.setFill(Color.GREEN);
        break;
    case 1:
        circle.setFill(Color.RED);
        break;
    case 2:
        circle.setFill(Color.BLUE);
        break;
    case 3:
        circle.setFill(Color.YELLOW);
        break;
    }
}

In this fashion, both position, radius and color is random. You can always change the values I used naturally, in this example the balls will vary from 20-49 in size and from 0-599 width and 0-399 height. Color is random between 4 different ones.

NON-RANDOM: If, however, you want to specifically set values for each circle, you can always access them individually by using the list.get(int index) to access the circles. You must also cast the list elements to the Circle type to be able to use Circle-specific methods. Here's an example:

((Circle)list.get(0)).setRadius(45.3);
((Circle)list.get(1)).setFill(Color.ORANGE);
((Circle)list.get(09).setCenterX(392);

However you have to personally be sure that the elements in the list are circles to use this kind of method. Your example provides this, but if you make a bigger program and the list contains other Nodes than Circle it might be harder to have the same level of control. If the list is only gonna be used for Circles then it might be a good idea to make it a List<Circle> type instead.

Upvotes: 0

Keno
Keno

Reputation: 2098

Why not create a new Circle instance in the for loop, modify it to your liking and then add it to the list?

List<Node> list = new ArrayList<>();

// Create circle dynamically
for(int i = 0; i < 10; i++) {
    Circle newCircle = new Circle();
    newCircle.setSize(i*2); //Just an example
    list.add(newCircle);
}

Upvotes: 0

Related Questions