Vaadin:如何让TextField按键事件在网格标题中触发?

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

提问人:James Asher 提问时间:11/9/2023 更新时间:11/22/2023 访问量:61

问:

Vaadin V24,爪哇。

我有一个网格,可以保存 PojoClass 的数据。在该网格的标题中,我有一个 TextField。当您在字段中键入内容并按 Enter 键时,该值将提交到服务器,并且将在网格中添加一个新行。问题是 Grid Header 内部有一些东西正在“窃取”我的回车键按下。附加到 TextField 的事件侦听器似乎从未触发过。取而代之的是,整个标题会得到一个蓝色的轮廓,就好像它刚刚获得了焦点一样。textField.addKeyPressListener(Key.ENTER, l -> submit())

下面是示例代码:

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()
);

这是蓝色轮廓的图片:picture of blue outline

如何让网格标头停止吞噬我的按键事件,以便调用事件侦听器函数?

Events Header Grid Vaadin 按键

评论


答:

0赞 Mirco Attocchi 11/22/2023 #1

在尝试使用 而不是textFieldkeyDownListeneraddKeyPressListener

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

在侦听器上,您还可以添加一个submit()

textField.focus();

将重点放在事件结束后是否松动textField