Search code examples
keyboard-shortcutsvaadinevent-propagation

Problems with using shortcuts in Vaadin


I have some problems with shortcuts in Table. I have to customize some keys: delete - for removing the rows and enter to make table editable/uneditable, up/down arrows to switch mode of table from editable to uneditable. I put my Table inside transparent Panel and use Action.Handler to catch keyboard events. But when I'm writing inside TextField, TextArea, Combobox I wanted to propagate events to this component (handling delete key disable using it for deleting text in TextField and up/down keys doesn't allow open Combobox with keyboard). I saw target parameter in handleAction() method, but I don't now how to use it. Also interesting to know how to add shortcuts instead of replacing.

    // adding table inside Panel
    tablePanel = new Panel();
    tablePanel.setStyleName(Panel.STYLE_LIGHT);

    VerticalLayout tableElementsLayout = new VerticalLayout();
    tablePanel.setContent(tableElementsLayout);

    tablePanel.setSizeFull();
    tableElementsLayout.setSizeFull();
    vl.addComponent(tablePanel);
    vl.setExpandRatio(tablePanel, 1.0f);

    tableElementsLayout.add(table);

    // --- adding keyboard handler
    final Action actionDel = new ShortcutAction("Delete",
            ShortcutAction.KeyCode.DELETE, null);

    deleteHandler = new Action.Handler() {

        @Override
        public void handleAction(Action action, Object sender, Object target) {
            // I want handle events here when I'm not inside TextField
        }

        @Override
        public Action[] getActions(Object target, Object sender) {
            return new Action[] { actionDel };
        }
    };

    tablePanel.addActionHandler(deleteHandler);        

Any ideas how to do that?


Solution

  • I'm not sure if this is the best or the most beautiful way to achieve this, but at least it works:

    textField.addListener(new BlurListener() {
        @Override
        public void blur(BlurEvent event) {
            tablePanel.addActionHandler(deleteHandler);
        }
    });
    
    textField.addListener(new FocusListener() {
        @Override
        public void focus(FocusEvent event) {
            tablePanel.removeActionHandler(deleteHandler);
        }
    });
    

    These listeners will take care of the deleteHandler by disabling it every time the user enters the field and enabling it whenever the user leaves the field.