Share the post "Sort JTree Node To Always Stay First Or Last"

Recently 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 as the first and last node.

For example, I want to make the String “CARS” to always be the first node in the JTree and the String “HOUSE” to be the last while the rest of the tree nodes will be sorted alphabetically.

Using the value of the compare() method of the Comparator class, I did a dirty workaround to make this work with a little help from the Math class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public int compare(Object o1, Object o2) { int output = o1.toString().compareToIgnoreCase(o2.toString()); if (o1.toString().equalsIgnoreCase("CARS")) { if (output > 0) { output = -Math.abs(output); } } else if (o2.toString().equalsIgnoreCase("CARS")) { if (output < 0) { output = Math.abs(output); } } else if (o1.toString().equalsIgnoreCase("HOUSE")) { if (output < 0) { output = Math.abs(output); } } else if (o2.toString().equalsIgnoreCase("HOUSE")) { if (output > 0) { output = -output; } } } |