Reputation: 39
Is it possible to deep copy a Label
(or any other node), so that it creates a new Label
object with the same property values and then put it in Dragboard
?
I want to implement this functionality: drag a label an drop it at some location in Pane
. A new Label
object with same property values is created in Pane at the location of the drop.
Upvotes: 0
Views: 1102
Reputation: 1498
As far as I know, Label
does not implement the Java Cloneable
interface, and so does not have any built in way to deep copy itself, nor does Node
.
You could create your own class which extends Label
and implements Cloneable
and in that class override the clone
method, and do that for every other Node
you wish to deep copy as well, this is the most robust solution, but it may be more than you need.
The other option is to just create a new Label with the same properties, which could be as simple as something like
Label newLabel = new Label(oldLabel.getText(), oldLabel.getGraphic());
Note that you may have problems with that method, as it is not a true deep copy, newLabel and oldLabel now reference the same Graphic Node, which again, you may have problems adding the same Graphic Node to the scene twice. A better copy might do something like
ImageView oldGraphic = (ImageView) oldLabel.getGraphic();
Label newLabel = new Label(oldLabel.getText(), new ImageView(oldGraphic.getImage());
This still isn't a true deep copy, but there are no rules against adding the same Image
to the scene as many times as you wish, so you're safe there. This sort of approach is fine for Labels, it's only two lines (it could be collapsed down to one even, but I went for more readability), but for more complex types of nodes could get really cumbersome. If it's just labels, here's an okay solution, but otherwise it would make sense to encapsulate all the needed copying into a new clone
method.
Upvotes: 1