flavio.donze flavio.donze - 2 months ago 30
Java Question

How to add Keylistener to ListSelect in Vaadin?

I have a vaadin

ListSelect
component on which I would like to remove items if the key
DEL
is used.

All I found was the
ShortcutListener
but if I add the following listener, the
DEL
key does not work in the rest of my application (e.g. deleting text in a
TextField
):

listSelect.addShortcutListener(new ShortcutListener("", KeyCode.DELETE, null) {
private static final long serialVersionUID = 4703134138899283799L;

@Override
public void handleAction(Object sender, Object target) {
// handle delete
}
});


How should I implement a listener for the
DEL
key?

EDIT: Tried to use a wrapper
Panel
as suggested in comments, but it still doesn't work. Here my current code:

listSelect = new ListSelect(null);
listSelect.setWidth(100, Unit.PERCENTAGE);
listSelect.setHeight(82, Unit.PIXELS);
listSelect.setMultiSelect(true);
listSelect.setNullSelectionAllowed(false);

listSelect.setDescription("Löschen mit der DEL Taste");
listSelect.addShortcutListener(new ShortcutListener("", KeyCode.DELETE, null) {
private static final long serialVersionUID = 4703134138899283799L;

@Override
public void handleAction(Object sender, Object target) {
// handle delete
}
});
Panel wrapperPanel = new Panel(listSelect);
form.addComponent(wrapperPanel);


The
form
is a
GridLayout
, the parent of
form
is a
Panel
. This panel is part of a
TabSheet
. I'm using Vaadin Version 7.7.1.

Answer

Looking at the sources (currently line 110), it seems that the action is delegated to the containing window...

/**
 * Keeps track of the Actions added to this component; the actual
 * handling/notifying is delegated, usually to the containing window.
 */
private ConnectorActionManager actionManager;

... or parent container at least, because based on this question Select-all shortcut (Ctrl-A) in Vaadin Table? you can work around this issue. If you wrap the list select in a panel and add the short-cut listener to the panel instead, it works as expected:

public class MyListSelectComponent extends VerticalLayout {

    public MyListSelectComponent() {
        ListSelect list = new ListSelect("Press DEL to remove items");
        TextField input = new TextField("Focus this input and press DEL to delete some text");
        input.setValue("This is some very long text, or not...");

        for (int i = 0; i < 10; i++) {
            list.addItem(i);
        }

        Panel panel = new Panel(list);
        panel.addShortcutListener(new ShortcutListener("", ShortcutAction.KeyCode.DELETE, null) {
            @Override
            public void handleAction(Object sender, Object target) {
                if (list.getValue() != null) {
                    list.removeItem(list.getValue());
                }
            }
        });

        addComponent(panel);
        addComponent(input);
    }
}

Actual output:

vaadin delete key shortcut listener

Comments