olimpiabaku
olimpiabaku

Reputation: 151

How to create copies of the same object (e.g Label)?

I want to add copies of a Label to a Pane.

Timeline timer = new Timeline(
        new KeyFrame(Duration.millis(1000),
                new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent actionEvent) {
                        Label egg_new = new Label();
                        egg_new = egg;
                        getChildren().add(egg_new);
                    }
                }));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();

It gives me an error because I can't add the same object to a Pane. How can I make a copy of egg? My label basically contains an egg icon, assume that my goal is to create a new copy of egg icon and add it to the Pane every second.

I tried copying the image of egg and setting it to egg_new but the egg dissapears then. This is how I do it:

Label egg_new = new Label();
ImageView egg_new_img = egg_img;
egg_new.setGraphic(egg_new_img);
getChildren().add(egg_new);

Upvotes: 0

Views: 63

Answers (1)

James_D
James_D

Reputation: 209553

Write a method to create the Label, and call it when you need one. That way you ensure the label is created the same way each time.

Note that no Node subclass instance can appear multiple times in the scene graph, so if you want the "same" Label you need to create a new Label each time, and create it in the same way. Similarly, if the Label has a graphic set, you need to create a new Node (e.g. ImageView) for the graphic each time.

private Image eggImage = ... ;

private Label createEggLabel() {
    Label eggLabel = new Label();
    ImageView eggImg = new ImageView(eggImage);
    eggLabel.setGraphic(eggImg);
    return eggLabel ;
}

and then

Timeline timer = new Timeline(
    new KeyFrame(Duration.millis(1000),
        event -> getChildren().add(createEggLabel())));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();

Upvotes: 3

Related Questions