Issue
I have a question which I think is based on my poor conceptual understanding of OOP/programming generally, but it has come up, specifically, in a JavaFX scenario.
I want to add a child node to parent node and then update that child, and see the update reflected, without having to remove it and re-add it to the parent node. Is this possible? More specifically, I have a Pane (parent) and an ImageView (child) which I want to add to the parent and then later modify.
Pane pane = new Pane();
ImageView picture = new ImageView("dog.png");
pane.getChildren().add(picture);
//now I'm seeing a picture of a dog in my Pane
picture = new ImageView("cat.png");
//So I've reassigned "picture" but am I still seeing a dog?
pane.getChildren().remove(picture);
pane.getChildren().add(picture);
//Am I seeing a cat now?
My apologies if this is unclear or too basic. I can attempt to clarify if needed. Any help is appreciated.
Solution
Reusing an existing ImageView
An ImageView is a view to an image.
You don't need to create a new view to view a new image, you can directly change the image you are viewing.
ImageView picture = new ImageView("dog.png");
Pane pane = new Pane(picture);
// . . .
// use alchemy to transmute a dog into a cat.
// . . .
picture.setImage(new Image("cat.png"));
Creating and using a new ImageView
You could make it work the way you originally coded it, though that is suboptimal. The change here is that you must remove the dog image view using the picture reference before you assign the picture reference to a new image view (not after as you did in your question).
Pane pane = new Pane();
ImageView picture = new ImageView("dog.png");
pane.getChildren().add(picture);
//now I'm seeing a picture of a dog in my Pane
// . . .
// remove the dog before you reassign the picture to a cat.
pane.getChildren().remove(picture);
picture = new ImageView("cat.png");
//So I've reassigned "picture" and can now see a cat, not a dog.
pane.getChildren().add(picture);
Answered By - jewelsea