Moving selection in Grid on arrow-key navigation?

When you click in grid and then use arrow keys to navigate, Vaadin highlights the currently focused cell, but it does not change the selection.

I want the row to be immediately selected. Can I do that?

The current behavior is made worse by the difference between:

  • single-select grids - User can select row with space
  • multi-select grids - No way to select
  • In open Editor row - No way to select / move

I have ARROW_UP/ARROW_DOWN shortcut listeners on Grid to move the editor, if it is open.
The listener also fires for the other two cases, but for those Vaadin has moved the cell, but I don’t have access to it, so can’t change the selection

Vaadin version: 24.9.4

Yes, you can do this with CellFocusListener. This listener fires when the focused cell changes, including keyboard navigation.

grid.addCellFocusListener(event -> {
    event.getItem().ifPresent(grid::select);
});

For multi-select grids, you probably want to clear previous selection first:

grid.addCellFocusListener(event -> {
    event.getItem().ifPresent(item -> {
        grid.deselectAll();
        grid.select(item);
    });
});

Or if you want arrow keys to move selection but keep multi-select behavior with Ctrl/Shift:

grid.addCellFocusListener(event -> {
    event.getItem().ifPresent(item -> {
        // Only single-select on plain navigation
        // User can still Ctrl+click for multi-select
        if (grid.getSelectedItems().size() <= 1) {
            grid.deselectAll();
            grid.select(item);
        }
    });
});

For your editor case: The CellFocusListener should not fire when the editor is open and you handle navigation yourself. But if it does, you can check:

grid.addCellFocusListener(event -> {
    if (grid.getEditor().isOpen()) {
        return; // Let your shortcut listener handle it
    }
    event.getItem().ifPresent(grid::select);
});

This approach gives you access to the focused item, which solves your problem of not knowing which cell Vaadin moved to.​​​​​​​​​​​​​​​​

Great Simon, exactly what I needed. :smiley:

Testing this, I’m having 2nd thoughts; Since the navigation now immediately changes the selection, and that triggers database operations, the navigation becomes sluggish.

I might want to switch to the Vaadin model for single-select lists; Let vaadin move around the cellFocus, and change the selection on Space. I’ll still need cellFocusListener to keep track of the current cell focus
Will have to check what the users prefer.

1 Like