Sort JTree

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.

Related Posts Plugin for WordPress, Blogger...

7 comments

  1. I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog list and will be checking back soon. Please check out my site as well and let me know what you think.

  2. Isn’t this really horrible performance-wise? You’re going to sort them for every node you add? You only want to sort them once after you’ve added them all.

  3. Yes…this is really bad performance wise since you are doing it on insert.

    On insert you should use Collections.binarySearch instead…it uses the same Comparator but instead will return you the insert index.

  4. int index = Collections.binarySearch(this.children, newChild, nodeComparator);

    if (index < 0) {
    super.insert(newChild, -index-1);
    }

    This will give log(n) run time compared with the sort's n log(n) performance.
    I guess this might only be significant for large tree's.

Leave a Reply

Your email address will not be published. Required fields are marked *