Mnemonics in GWT

2019-08-31 03:38发布

问题:

I would like to create as Java Swing Mnemonics with GWT . But I don't know how to figure it out. I have googled for it but I didn't fond any sample codes for it . I want to bind some keyboard shortcut keys on my buttons. How can I achieve it ? Any suggestions would be really appreciated !

回答1:

In general you can handle global keyboard shortcusts using a NativePreviewHandler. An example of this can you see here:

NativePreviewHandler nativePreviewHandler = new NativePreviewHandler() {

    @Override
    public void onPreviewNativeEvent(NativePreviewEvent event) {
        if (event.getTypeInt() != Event.ONKEYDOWN) {
            return;
        }
        final NativeEvent nativeEvent = event.getNativeEvent();
        final boolean altKey = nativeEvent.getAltKey();
        final boolean ctrlKey = nativeEvent.getCtrlKey();
        if(altKey && ctrlKey && nativeEvent.getKeyCode() == 'A') {
            // Do Something
        }
    }
};
Event.addNativePreviewHandler(nativePreviewHandler);

But as far as I klnow, there's no generic way build into GWT to handle some kind of Action that is bound to a button/Menu as well as a keyboard shortcut. You will have to implement such an abstraction by yourselves.



回答2:

I hope this code will help you. Here we are adding a key down handler on document element.

RootPanel.get().addDomHandler(new KeyDownHandler() {

        @Override
        public void onKeyDown(KeyDownEvent event) {
            if (event.isControlKeyDown()) {
                char ch = (char) event.getNativeKeyCode();
                if (ch == 's' || ch == 'S') {
                    // do operation for Ctrl+S
                } else if (ch == 'c' || ch == 'C') {
                    // do operation for Ctrl+C
                }
                // add more or use switch case
            }
        }
    }, KeyDownEvent.getType());


标签: gwt gwt2