I had a related Problem, with special tree table sorting. I ended up writing my own Container and Comperator implementation.
Your question depends on the container you are using, since the sorting is done by the the underlying container and not the table. By default TreeTable uses the HierarchicalContainer implementation, where you could use your own ItemSorter implementation. You could extend DefaultItemSorter and distinguish different cases when comparing two elements:
- Two leaf elements having the same parent:
use DefaultItemSorter.compare() - Two parent elements having the same parent (also null):
return the value to keep the order you want - An element to one in its path to the root:
return a value so the deeper element is after the higher. - Two elements not having the same parent:
In both paths go up the tree until you find the depth where the next parents are the same and compare these two elements. Start with the deeper element and go up until you are on the same level as the other.
I hope i didn't forget a case. Anyway I advise you to write several unit tests to be sure your ItemSorter does the right thing in all the cases.
If you know that your tree has special characteristics, like the maximal depth is two, you might simplify the ItemSorter. I couldn't see that from your question. Please add more details next time.