package be.nikiroo.utils.ui; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; public abstract class DataTree { private DataNode data; public DataNode loadData() throws IOException { return this.data = extractData(); } public DataNode getRoot() { return getRoot(null); } public DataNode getRoot(String filter) { return filterNode(data, filter); } protected abstract DataNode extractData() throws IOException; // filter cannot be null nor empty protected abstract boolean checkFilter(String filter, E userData); protected boolean checkFilter(DataNode node, String filter) { if (filter == null || filter.isEmpty()) { return true; } if (checkFilter(filter, node.getUserData())) return true; for (DataNode child : node.getChildren()) { if (checkFilter(child, filter)) return true; } return false; } protected void sort(List values) { Collections.sort(values, new Comparator() { @Override public int compare(String o1, String o2) { return ("" + o1).compareToIgnoreCase("" + o2); } }); } // note: we always send TAHT node, but filter children private DataNode filterNode(DataNode source, String filter) { List> children = new ArrayList>(); for (DataNode child : source.getChildren()) { if (checkFilter(child, filter)) { children.add(filterNode(child, filter)); } } return new DataNode(children, source.getUserData()); } // TODO: not in this class: public void loadInto(DefaultMutableTreeNode root, String filter) { DataNode filtered = getRoot(filter); for (DataNode child : filtered.getChildren()) { root.add(nodeToNode(child)); } } private MutableTreeNode nodeToNode(DataNode node) { // TODO: node.toString DefaultMutableTreeNode otherNode = new DefaultMutableTreeNode( node.toString()); for (DataNode child : node.getChildren()) { otherNode.add(nodeToNode(child)); } return otherNode; } }