Search code examples
tableviewjavafx-8comparable

Intercept sorting the items of a JavaFX 8 TableView


I have an applications that hosts a TableView. Whenever the user sorts the rows by clicking the header of a particular column, I need to

  1. Save the current order of items,
  2. Do the actual sorting,
  3. Save the new order of items.

I was able to spot this:

this.tableView.sortPolicyProperty().set(t -> {
        System.out.println("saving source order");
        ... // Saving
        FXCollections.sort(tableView.getItems(), t.getComparator());
        System.out.println("saving target order");
        ... // Saving
        return true;
});

However, this throws ClassCastException pretty often. Is there a better way of saving the item permutations before and after sorting?


Solution

  • You could listen to it using the ListChangeListener the better way :)

    tv.getItems().addListener(new ListChangeListener<T>(){
                @Override
                public void onChanged(javafx.collections.ListChangeListener.Change<
                                       ? extends T> c) {        
                while(c.next()){
                  if(c.wasPermutated()){
                       System.out.println("is permuated");
                  }
               }
           }
    
    });
    

    Hope it helps.