Sort JTree
Posted by tech on
November 15, 2009
Sorting a JTree’s nodes is easy. Just make sure your nodes are of type DefaultMutableTreeNode. Have your class extend DefaultMutableTreeNode and add this code within the class. As you can see in the code, once a tree node is inserted into the tree, the nodes are sorted alphabetically using the Collections‘ sort method.
@Override public void insert(MutableTreeNode newChild, int childIndex) { super.insert(newChild, childIndex); Collections.sort(this.children, nodeComparator); } protected Comparator nodeComparator = new Comparator () { @Override public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object obj) { return false; } @Override public int hashCode() { int hash = 7; return hash; } };

/rating_on.png)








November 16th, 2009 at 3:30 am
i Also like this script
November 17th, 2009 at 6:53 pm
[...] I wrote a post on how to sort JTree nodes alphabetically. But what if you want certain nodes that are equal to some words and you want them to always stay [...]