ItEr17S07RFComportamentoGraficoPlanificadorItEr16S09: Adding methods to navigate through parents of a node.

This commit is contained in:
Óscar González Fernández 2009-07-13 14:01:41 +02:00 committed by Javier Moran Rua
parent 2c812f4d65
commit 0f4a338192
2 changed files with 63 additions and 0 deletions

View file

@ -1,5 +1,6 @@
package org.zkoss.ganttz.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -62,6 +63,10 @@ public class MutableTreeModel<T> extends AbstractTreeModel {
return positionInParent;
}
public Node<T> getParent() {
return parentNode;
}
}
private final Class<T> type;
@ -168,4 +173,26 @@ public class MutableTreeModel<T> extends AbstractTreeModel {
TreeDataEvent.INTERVAL_REMOVED);
}
public T getParent(T node) {
Node<T> associatedNode = find(node);
if (associatedNode.equals(root))
throw new IllegalArgumentException(node + " is root");
return unwrap(associatedNode.getParent());
}
public List<T> getParents(T node) {
ArrayList<T> result = new ArrayList<T>();
T current = node;
while (!isRoot(current)) {
current = getParent(current);
result.add(current);
}
return result;
}
public boolean isRoot(T node) {
Node<T> associatedNode = find(node);
return associatedNode.isRoot();
}
}

View file

@ -9,6 +9,7 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
@ -112,6 +113,41 @@ public class MutableTreeModelTest {
assertThat(model.getPath(child, root), equalTo(new int[0]));
}
@Test
public void hasMethodGetParentToMakeNavigationEasier() {
Prueba root = new Prueba();
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class,
root);
Prueba child = new Prueba();
model.add(root, child);
Prueba grandChild = new Prueba();
model.add(child, grandChild);
assertThat(model.getParent(grandChild), equalTo(child));
assertThat(model.getParent(child), equalTo(root));
}
@Test
public void hasMethodGetAllParentsUntilRoot() {
Prueba root = new Prueba();
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class,
root);
Prueba child = new Prueba();
model.add(root, child);
Prueba grandChild = new Prueba();
model.add(child, grandChild);
List<Prueba> parents = model.getParents(grandChild);
assertThat(parents.size(), equalTo(2));
assertThat(parents, equalTo(Arrays.asList(child, root)));
}
@Test(expected = IllegalArgumentException.class)
public void getParentOfRootThrowsException() {
Prueba root = new Prueba();
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class,
root);
model.getParent(root);
}
@Test
public void addingTriggersEvent() {
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class);