Merge branch 'subtree'
[nikiroo-utils.git] / ui / DataNode.java
CommitLineData
a917f100
NR
1package be.nikiroo.utils.ui;
2
3import java.util.ArrayList;
4import java.util.Arrays;
5import java.util.List;
6
7import javax.swing.Icon;
8
9public class DataNode<T> {
10 private DataNode<T> parent;
11 private List<? extends DataNode<T>> children;
12 private T userData;
13
14 public DataNode(List<? extends DataNode<T>> children, T userData) {
15 if (children == null) {
16 children = new ArrayList<DataNode<T>>();
17 }
18
19 this.children = children;
20 this.userData = userData;
21
22 for (DataNode<T> child : children) {
23 child.parent = this;
24 }
25 }
26
27 public DataNode<T> getRoot() {
28 DataNode<T> root = this;
29 while (root.parent != null) {
30 root = root.parent;
31 }
32
33 return root;
34 }
35
36 public DataNode<T> getParent() {
37 return parent;
38 }
39
40 public List<? extends DataNode<T>> getChildren() {
41 return children;
42 }
43
44 public int size() {
45 return children.size();
46 }
47
48 public boolean isRoot() {
49 return this == getRoot();
50 }
51
52 public boolean isSiblingOf(DataNode<T> node) {
53 if (this == node) {
54 return true;
55 }
56
57 return node != null && parent != null && parent.children.contains(node);
58 }
59
60 public boolean isParentOf(DataNode<T> node) {
61 if (node == null || node.parent == null)
62 return false;
63
64 if (this == node.parent)
65 return true;
66
67 return isParentOf(node.parent);
68 }
69
70 public boolean isChildOf(DataNode<T> node) {
71 if (node == null || node.size() == 0)
72 return false;
73
74 return node.isParentOf(this);
75 }
76
77 public T getUserData() {
78 return userData;
79 }
80
2da37d38
NR
81 /**
82 * The total number of nodes present in this {@link DataNode} (including
83 * itself and descendants).
84 *
85 * @return the number
86 */
87 public int count() {
88 int s = 1;
a917f100
NR
89 for (DataNode<T> child : children) {
90 s += child.count();
91 }
92
93 return s;
94 }
95
96 @Override
97 public String toString() {
98 if (userData == null) {
99 return "";
100 }
101
102 return userData.toString();
103 }
104}