From: Marc Englund Date: Fri, 1 Feb 2008 11:34:50 +0000 (+0000) Subject: AbstractComponent.setParent(parent) cannot be called if component already has parent... X-Git-Tag: 6.7.0.beta1~5118 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=8a30d9ec793b343e48ff4ec05391be0fca1cd9d0;p=vaadin-framework.git AbstractComponent.setParent(parent) cannot be called if component already has parent, unless the new parent is null (unsetting parent). AbstractComponentContainer.addComponent(component) removes the component from it's previous ComponentContainer if needed (moves component), or throws if the component can't be removed. Fixes #1137 All components that contain other components should implement ComponentContainer for this to be perfect (e.g CustomComponent, Table) svn changeset:3698/svn branch:trunk --- diff --git a/src/com/itmill/toolkit/ui/AbstractComponent.java b/src/com/itmill/toolkit/ui/AbstractComponent.java index 73afcb6aa8..3508266d91 100644 --- a/src/com/itmill/toolkit/ui/AbstractComponent.java +++ b/src/com/itmill/toolkit/ui/AbstractComponent.java @@ -450,15 +450,18 @@ public abstract class AbstractComponent implements Component, MethodEventSource */ public void setParent(Component parent) { - // If the parent is not changed, dont do nothing + // If the parent is not changed, don't do anything if (parent == this.parent) { return; } + if (parent != null && this.parent != null) { + throw new IllegalStateException("Component already has a parent."); + } + // Send detach event if the component have been connected to a window if (getApplication() != null) { detach(); - this.parent = null; } // Connect to new parent diff --git a/src/com/itmill/toolkit/ui/AbstractComponentContainer.java b/src/com/itmill/toolkit/ui/AbstractComponentContainer.java index 5251e99438..d0169535b7 100644 --- a/src/com/itmill/toolkit/ui/AbstractComponentContainer.java +++ b/src/com/itmill/toolkit/ui/AbstractComponentContainer.java @@ -169,6 +169,30 @@ public abstract class AbstractComponentContainer extends AbstractComponent * @see com.itmill.toolkit.ui.ComponentContainer#addComponent(Component) */ public void addComponent(Component c) { + if (c instanceof ComponentContainer) { + // Make sure we're not adding the component inside it's own content + for (Component parent = this; parent != null; parent = parent + .getParent()) { + if (parent == c) { + throw new IllegalArgumentException( + "Component cannot be added inside it's own content"); + } + } + } + + if (c.getParent() != null) { + // If the component already has a parent, try to remove it + try { + ComponentContainer oldParent = (ComponentContainer) c + .getParent(); + oldParent.removeComponent(c); + } catch (Exception e) { + throw new IllegalStateException( + "Component could be removed from it's old parent."); + } + + } + c.setParent(this); fireComponentAttachEvent(c); }