Custom treetableview order

163 views Asked by At

I have a treetableview which multiple columns. I like to order only by one column so I apply:

treetbvItems.getSortOrder().add("categoria");

This order data by column "categoria" alphabetical but I want to apply my custom order.

For example, if category can be onew of this values: animals, computers, shoes, vehicles... with above sentence, I get tree order by this way:

  1. animals
  2. computers
  3. shoes
  4. vehicles

but if I want (can be any other custom orther):

  1. computers
  2. shoes
  3. animals
  4. vehicles

Is possible or not to do whith JavaFX?

1

There are 1 answers

1
James_D On BEST ANSWER

I assume you really mean

TreeTableColumn<String> categoria ; 
// ...

treebvItems.getSortOrder().add(categoria);

since the code you posted won't compile.

You can control the ordering for a particular column by setting a Comparator on the column.

The Comparator defines a compareTo(String, String) method that returns an negative int if the first argument comes before the second, a positive int if the second argument comes before the first, and 0 if they are equal.

So you could do something like:

categoria.setComparator((cat1, cat2) -> {
    if (cat1.equals(cat2)) {
        return 0 ;
    }
    if ("computers".equals(cat1)) {
        return -1 ;
    }
    if ("computers".equals(cat2)) {
        return 1 ;
    }
    if ("shoes".equals(cat1)) {
        return -1 ;
    }
    if ("shoes".equals(cat2)) {
        return 1 ;
    }
    if ("animals".equals(cat1)) {
        return -1 ;
    }
    if ("animals".equals(cat2)) {
       return 1 ;
    }
    throw new IllegalArgumentException("Unknown categories: "+cat1+", "+cat2);
}

Note that if you have a fixed set of categories, you should probably use an Enum instead of a String. The "natural" order of an Enum is defined by its declaration order.