javazkzul

How to subscribe KeyEvent in ZK 7.X


We are creating a Window to add attachments. The attachments can be added by either Drag N Drop or using Ctrl+V to copy from the clipboard. Able to implement Drag and Drop but unable to subscribe KeyEvent on the Window or Page.

Tried the following codes but failed:

  1. onPageAttached & onPageDetached

    @Override
    public void onPageDetached(Page page) {
        super.onPageDetached(page);
        try {
            SessionManager.getSessionApplication().getKeylistener().removeEventListener(Events.ON_CTRL_KEY, this);
        } catch (Exception e) {}
    }
    
    @Override
    public void onPageAttached(Page newpage, Page oldpage) {
        super.onPageAttached(newpage, oldpage);
        if (newpage != null) {
            SessionManager.getSessionApplication().getKeylistener().addEventListener(Events.ON_CTRL_KEY, this);
        }
    } 
    
  2. addEventListener inside the custom Window class which implements EventListener.

    this.addEventListener(Events.ON_CTRL_KEY, this);

All the code sample that I could see on the web is with ZUL file. But I need to achieve this using java code dynamically.

I am able to subscribe to other events like click event, on close, etc.


Solution

  • You have a few things to configure to listen to keys:

    1: the target If you want to listen to keys in the whole page, the first thing you need is to declare this library property in your zk.xml: https://www.zkoss.org/wiki/ZK_Configuration_Reference/zk.xml/The_Library_Properties/org.zkoss.zk.ui.invokeFirstRootForAfterKeyDown.enabled with a value of "true"

    This library property redirects every key listener event to the root component of your page. If you don't set it, you will only be able to listen to keys on a component when it has focus.

    2: the key declaration You need to declare which keys you listen to with comp.setCtrlKeys(ctrlKeys); where ctrlKeys is a string containing the keys you want to listen to for example, ctrl+v would be comp.setCtrlKeys("^v");

    3: the listener Your sample code already have a version of this. You can use the add addEventLister(this) syntax, but it's over complicating the task. simplest option is to inline the listener if you are not reusing it:

    //comp here is the root div of my page
    comp.setCtrlKeys("^v");
    comp.addEventListener(Events.ON_CTRL_KEY, new EventListener<Event>() {
        @Override
        public void onEvent(Event event) throws Exception {
            Clients.log("do something at page level");
        }
    });
    

    See this fiddle !!!! THIS FIDDLE CANNOT WORK FROM PAGE LEVEL !!!! due to library property not being settable on zkfiddle. Just run it locally with your zk.xml including the property above to have page-level listeners.