Tree sugestion: recursive adding

Instead of using Objects in the addItem function, I think that its a good idea to use another generic class that have a parent description, so when we add an “father” item, all the children should be added too…

I implemented a simple class like this:

import java.util.ArrayList;

public class Produt {

	public String name;
	public ArrayList<Produt> children= new ArrayList<Produto>();
	
	public Produt(String name) {
		this.name = name;
	}
	public void addChild(Produt child) {
		children.add(child);		                
	}
	
	public boolean hasChild() {
		if (children.isEmpty() == true) {
			return false;
		} else {
			return true;
		}
	}
}

and overrideded addItem like this:

public Item addItem(Object itemId) {
    	Produt father =  (Produto) itemId;
    	Produt child;
    	if (father.hasChild()) {
    		super.addItem(father.name);
    		for (Iterator it = father.children.iterator(); it.hasNext(); ) {
    			child = (Produto) it.next();
    			if (child.hasChildren()) {
    				addItem(child);
    				setParent(child.name, father.name);
    			} else {
    				super.addItem(child.name);
    				setParent(child.name, father.nome);
    				setChildrenAllowed(child.name, false);
    			}
    		}
    		return null;    		
    	} else {
    		return super.addItem(father.name);	
    	}    		    	
    }

Hi! Nice suggestion. However - would it not be easier to have that code in the view, instead of overriding the tree itself. Like this:

public Item addProdut(Produt father) {
    	Produt child;
    	if (father.hasChild()) {
    		tree.addItem(father.name);
    		for (Iterator it = father.children.iterator(); it.hasNext(); ) {
    			child = (Produto) it.next();
    			if (child.hasChildren()) {
    				tree.addItem(child);
    				tree.setParent(child.name, father.name);
    			} else {
    				tree.addItem(child.name);
    				tree.setParent(child.name, father.nome);
    				tree.setChildrenAllowed(child.name, false);
    			}
    		}
    		return null;    		
    	} else {
    		return super.addItem(father.name);	
    	}    		    	
    }

Of course, the benefit of your code can be used directly in multiple views, and that can only be used in one, you could move this to a util class and let the method take an tree in too (addProdut(Produt father, Tree tree)). I may only be my own opinion, but I like to use the normal API of components instead of override it. I think the code is more reliable that way, if you update the Vaadin package and the tree-code has changed.

Hi Jens I have tried your solution without any success. Have you tried that out to see if that works ?