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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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;
    }
};

Found this post useful? Buy me a cup of coffee or subscribe to my RSS feeds and Google Friend Connect

Related Posts with Thumbnails

tags: ,

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

  3. 3
    Chadwick Zalamea Says:

    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.

Leave a Reply

Spam protection by WP Captcha-Free