简体   繁体   中英

Vaadin Grid - specific rows always on top

I have two classes, one named "Folder" and the second one "Item". I'm using an interface to show folders and items together in one Vaadin Grid. I wrote a custom comparator to have folders and items sorted correctly (folders on top). But the problem is that users are able to change the sort order and then the folders are on bottom. My question is how to have folders always on top? Is it possible to detect the selected order in the comparator?

在此处输入图像描述

grid.addColumn(e -> e.getName())
        .setHeader("Name")
        .setSortable(true)
        .setComparator((item1, item2) -> {
            if (item1 instanceof Folder && item2 instanceof Item) {
                return -1;
            } else if (item1 instanceof Item && item2 instanceof Folder) {
                return 1;
            } else {
                return item1.getName().compareTo(item2.getName());
            }
        })

You'd need a comparator that always first orders based on the category (folder vs item in your case) and then order by the actual column value to resolve ties. To make things slightly more complicated, the same comparator is used regardless of whether the sort order is ascending or descending. You would need to compensate for this by making the category comparison order compensate for the sort order of the column to ensure that reverse ordering wouldn't put the folders last.

I implemented a simple proof of concept for this idea below, but you might need to make some tweaks to the concept in case you could have null values there or if you need to support sorting on multiple columns at the same time.

@Route
public class View1 extends VerticalLayout {
    record Item(String category, String name) { }

    public View1() {
        Grid<Item> grid = new Grid<Item>();
        grid.addColumn(Item::category).setHeader("Category");
        grid.addColumn(Item::name).setHeader("Name").setSortable(true).setComparator((a, b) -> {
            int categoryOrder = a.category.compareTo(b.category);
            if (categoryOrder == 0) {
                return a.name.compareTo(b.name);
            }
            return grid.getSortOrder().get(0).getDirection() == SortDirection.ASCENDING ? categoryOrder
                    : -categoryOrder;
        });
        grid.setItems(new Item("a", "a"), new Item("a", "c"), new Item("a", "b"), new Item("b", "a"),
                new Item("b", "c"), new Item("b", "b"));

        add(grid);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM