]> source.dussan.org Git - vaadin-framework.git/commitdiff
AbstractComponent.setParent(parent) cannot be called if component already has parent...
authorMarc Englund <marc.englund@itmill.com>
Fri, 1 Feb 2008 11:34:50 +0000 (11:34 +0000)
committerMarc Englund <marc.englund@itmill.com>
Fri, 1 Feb 2008 11:34:50 +0000 (11:34 +0000)
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

src/com/itmill/toolkit/ui/AbstractComponent.java
src/com/itmill/toolkit/ui/AbstractComponentContainer.java

index 73afcb6aa81e4820aa709320745ea30fda4afb06..3508266d91754b81513a48c1dd2c274ad26b22d9 100644 (file)
@@ -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
index 5251e99438ffac5c35d0243e58d27329db181c38..d0169535b7ea9d13f1ab234de0ffbbd74573adcd 100644 (file)
@@ -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);
     }