Vaadin: How to get TextField keypress event to fire when in a Grid Header?

109 Views Asked by At

Vaadin V24, Java.

I have a grid that will hold data of, let's say, PojoClass. In the header of that grid, I have a TextField. When you type something into the field and press the Enter key, the value is submitted to the server and a new line will be added to the grid. The issue is that there's something internal to the Grid Header that is "stealing" my enter key press. The event listener that's attached to the TextField via textField.addKeyPressListener(Key.ENTER, l -> submit()) never seems to fire. Instead, the entire header gets a blue outline as if it's just gained focus.

Below is example code:

Grid<PojoClass> grid = new Grid<>(PojoClass.class,false);
// grid set up here...

Grid.Column<PojoClass> column1 = cycleCountLinesGrid.addColumn(PojoClass::getSomething1)
    .setFlexGrow(1)
    .setHeader("Something1");

Grid.Column<PojoClass> column2 = cycleCountLinesGrid.addColumn(PojoClass::getSomething2)
    .setFlexGrow(1)
    .setHeader("Something2");

HeaderRow headerRow = grid.prependHeaderRow();
HeaderRow.HeaderCell headerRowCell = headerRow.join(
    column1,
    // must have at least two columns here
    column2
);

TextField textField = new TextField();
textField.setClearButtonVisible(true);
textField.setWidth(350, Unit.PIXELS);
textField.setSuffixComponent(UIUtils.createButton(VaadinIcon.ENTER, l -> submit()));
textField.setPattern("^[0-9]+$|^[Cc][0-9]*$|^[Cc]?[Ee]?[Vv]?[Aa]?[0-9]*$");
textField.addKeyPressListener(Key.ENTER, l -> submit());

headerRowCell.setComponent(
    new FlexBoxLayout(
        UIUtils.createH3Label("Scanned Items")
            .withDisplay(Display.INLINE_BLOCK)
            .withClassNames(LumoStyles.Margin.Right.M)
    ).space().with(
            UIUtils.createH4Label("Scan Item")
                .withDisplay(Display.INLINE_BLOCK)
                .withClassNames(LumoStyles.Margin.Right.M),
            textField
        )
        .withFlexDirection(FlexLayout.FlexDirection.ROW)
        .withBoxSizing(BoxSizing.BORDER_BOX)
        .withAlignItems(FlexComponent.Alignment.CENTER)
        .withJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN)
        .withSizeFull()
);

Here's an picture of the blue outline: picture of blue outline

How can I get the grid header to stop swallowing my key press event so that event listener function gets called?

1

There are 1 best solutions below

0
Mirco Attocchi On

on the textField try to use the keyDownListener instead of addKeyPressListener

textField.addKeyDownListener(Key.ENTER, l -> submit());

on submit() listener you can add also a

textField.focus();

to take focus on the textField if it's loosed after the event