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.

@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;
    }
};
Bookmark and Share

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading ... Loading ...

tags: ,

2 Responses to “Sort JTree”

  1. 1
    rizky2009 Says:

    i Also like this script

  2. 2
    Sort JTree Node To Always Stay First Or Last | Tech Tips Tricks Says:

    [...] 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 [...]

Leave a Reply