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

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 [...]
April 11th, 2010 at 4:33 am
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.