Sort JTree Node To Always Stay First Or Last
Posted by admin on
November 17, 2009
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.
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; } } }







