Search code examples
javaevent-handlingswtjface

How to handle KeyEvent's for each ViewPart or Form in SWT/JFace?


I'm building an Eclipse application and I'm trying to make a shortcut for launching an action when pressing F5, and make that the default action when that Tab/ViewPart has the focus.

I have read that this is not possible, or very complex. Is there any simple/straight way of doing it?

I tried with:

Display.getCurrent().addFilter(...)
this.addKeyListener(new KeyAdapter() {...})

...

Making this in the constructor is my best:

this.getShell().addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
        if(e.keyCode == SWT.F5) {
            //doAnything()
        }
    }
});

And this doesn't work when loaded, but if I switch from this to another View/Tab starts to work. But it works too when others have focus (which I don't want).

Is there anyway of making this work at the start, and only when the focus is in the View?


Solution

  • You should define work in a handler & then should use key bindings as given in this example. You can find a good example here. Hope it solves your need.