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:
but if I want (can be any other custom orther):
Is possible or not to do whith JavaFX?
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.