vaadin flow caputure enter key for text area

Viewed 11

I'm using a classed derived from the vaadin Dialog.

The dialog has a TextArea and an OK button. The OK button has a shortcut defined for the enter key. Whilst in the TextArea i want to disable the shortcut on the enter key so the textarea receives the enter key and the dialog doesn't close.

I've managed to disable the shortcut however my problem is that the textarea doesn't receive the new line character so the user remains on the current line.

I need a method which disables the shortcut enter key but still passes the keystroke to the text area.

I'm looking for a generic solution here that allows me to capture the enter key without knowledge of the current owner of the shortcut. e.g. a solution that has the code temporarily remove the shortcut on the OK button by having access to the OK button isn't acceptable.

Whilst I've given a a specific use case here I'm trying to use this technique throughout my code where ever I use a TextArea. In many cases I won't know or have access to the 'owner' of the shortcut.

protected Component buildContent(VLayout layout)
{
        private TextArea inputField = new TextArea();
        layout.add(inputField);

        Shortcuts.addShortcutListener(this,
                    (e) -> {
                        // this is ugly (will cause flashing) and doesn't 
                        // actually work as the call
                        // to inputField.getValue() returns an empty string.
//                      System.out.println(inputField.getValue() );
//                      inputField.setValue(inputField.getValue() + "\n");
                    }, Key.ENTER)
                .listenOn(inputField);

        

        return layout;
    }
    

I've also tried being 'clever' but nesting the listeners. The idea here is that the listener on the textarea captures the shortcut but allows it to propergate (hopefully into the textarea) but then the second listener attached to the layout would stop the event propergating up to the enter OK button.

The OK button doesn't receive the event but neither does the textarea.


    protected Component buildContent3(VLayout layout)
    {

        // first parameter is the lifecycle owner
        // of the shortcut and will be discussed later.

        Shortcuts.addShortcutListener(this,
                (e) ->
                    {
                        System.out.println("shortcut-inputfield");
                    },
                Key.ENTER)
                .listenOn(inputField)
                .allowEventPropagation();

        Shortcuts.addShortcutListener(this,
                (e) ->
                    {
                        System.out.println("shortcut-layout");
                    },
                Key.ENTER)
                .listenOn(layout);

        return layout;
    }
0 Answers
Related