Home > Software design >  Change icon on a selected row in a Vaadin Grid
Change icon on a selected row in a Vaadin Grid

Time:11-08

So, I have a grid called "eventGrid". I added a component column with a down-arrow icon. When a user clicks on a row, addition information is displayed for that row. I want to change the down arrow to an up arrow for the selected row. How can I achieve this?

 eventGrid.addColumn(Person::getFirst).setHeader("First Name");
    eventGrid.addColumn(Person::getLast).setHeader("Last Name");
    eventGrid.addColumn(Person::getNumber).setHeader("Phone Number");


 eventGrid.addComponentColumn(item -> {
      Icon icon = new Icon("lumo", "angle-down");
      return icon;
    }).setWidth("6em").setFlexGrow(0);

CodePudding user response:

There are two steps to the solution. First you need to make the renderer react differently for selected items and second, you need to make the grid re-render the row for which the selected status changes.

The first part can be handled in the component renderer:

eventGrid.addComponentColumn(item -> {
    String name = eventGrid.getSelectedItems().contains(item) ? "angle-down" : "angle-up";
    Icon icon = new Icon("lumo", name);
    return icon;
}).setWidth("6em").setFlexGrow(0);

The second part is a listener that uses DataProvider::refreshItem to trigger specific rows to be rendered again. This is implemented through asSingeSelect to get an event that contains both the old and the new value.

eventGrid.asSingleSelect().addValueChangeListener(event -> {
    String newValue = event.getValue();
    String oldValue = event.getOldValue();

    if (newValue != null) {
        eventGrid.getDataProvider().refreshItem(newValue);
    }
    if (oldValue != null) {
        eventGrid.getDataProvider().refreshItem(oldValue);
    }
});

CodePudding user response:

Assuming you have an in-memory DataProvider:

        Grid<Person> eventGrid = new Grid<Person>();
        eventGrid.addColumn(Person::getFirst).setHeader("First Name");
        eventGrid.addColumn(Person::getLast).setHeader("Last Name");
        eventGrid.addColumn(Person::getNumber).setHeader("Phone Number");
        eventGrid.addComponentColumn(item -> {
            Icon icon = new Icon("lumo", "angle-down");
            if (item.equals(eventGrid.asSingleSelect().getValue())) {
                icon = new Icon("lumo", "angle-up");
            }
            return icon;
        }).setWidth("6em").setFlexGrow(0);
        eventGrid.addSelectionListener(e -> {
            eventGrid.getListDataView().refreshAll();
        });
  • Related