SWT Global KeyListener Button Focus Problem

十年热恋 提交于 2019-12-01 09:18:29

You can use TraverseListener and disabled press event detection using doin field. Here is a sample code:

display.addFilter(SWT.KeyDown, new Listener() {
    public void handleEvent(Event e) {
        if (e.character == 32) {
            System.out.printf("Space detected %s\n", e);
        }
    }
});

Button b1 = new Button(shell, SWT.PUSH);
b1.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent se) {
        System.out.printf("Button pressed %s\n", se);
    }
});

b1.addTraverseListener(new TraverseListener() {
    @Override
    public void keyTraversed(TraverseEvent te) {
        System.out.printf("Traverse detected %s\n", te);
        te.doit = true;
    }
});

If addTraverseListener() didn't exist, your space button was detected after filter, so you would see "Space detected..." and after that "Button pressed...". Now that you set te.doit = true, you say to SWT to do space bar traversal (which does nothing actually) instead of firing key listener. You may optionally check te.detail to only prevent mnemonic traversals.

Choosing the 'Space key' is the real problem, because it is a general feature in most (all?) OS's that pressing space is equal to selecting the widget that has focus.

A way out would be using subclassed Button widgets that ignoring Space.

But it would confuse a lot of users, just because they expect that a focussed button is selected when they hit space and do not expect some other action.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!