How to sort glazed TreeList?

2019-08-02 19:06发布

问题:

I have a pretty weird question - how to sort glazed TreeList? I am using it in SWT NatTable, and when my data provider is set to GlazedListsDataProvider with TreeList inside it, sorting works in a very strange way. It works fine, if I am using GlazedListsDataProvider with SortedList.

For instance, my tree looks like that:

Root
  Node1
   Child1
   Child2
  Node2
   Child3

I need to sort only children INSIDE Node1 and Node2, separately one of another (so that only child1 and child2 will change their place). However, After sorting it looks like following:

Root
  Node1
  Node2
   Child1
   Child2
   Child3

Reversed sorting:

Root
  Node1
  Node2
   Child2
   Child1
   Child3

So basically, it kind of working (it does sort children in a correct way), but moreover it sorts elements, which it should not sort. What could be a reason of such behavior? My sorting algorithm is simple:

compare (element1, element2) {
   if (both elements are under same parent and have same type)
     compare
   otherwise
     return 0
   }

I am doing sorting as proposed in following example http://kari.dy.fi/src/sample/foldertree.zip - meaning, that after comparator is build in SortState I am setting it into the TreeFormat, used by TreeList.

I assume, that returning 0 does not work in a correct way, however, I can not see other solution. Or may be it is a problem somewhere else, not in my comparator.

Thank you for your patience, I will be glad to get any hints. Best regards, Alex G.

回答1:

Your current code returns 0 when to nodes have different parents. That's like, 'if they have different parents, I don't care which one goes first'. But I think you want, 'if they have different parents, the first should be the one with the first parent'. If you want to do custom sorting inside the parents only, you should keep sorting outside the parents the way it was. Not sure about the exact code, but you could do something like:

compare (element1, element2) {
   if (both elements are under same parent and have same type)
     compare
   otherwise
     return original.compare(element1,element2)//delegate to the original sorting
   }

Or

compare (element1, element2) {
   if (both elements are under same parent and have same type)
     compare
   otherwise
     compare(element1.parent,element2.parent) // sort on parent level
   }


回答2:

So, here is my solution for this problem: DZone Article. Once again, it is only one of the possible solutions, and it is not perfect, but it is working:)