Search code examples
javaeclipseswt

Add SWT context menu in SWT Table with Shortcut Keys


I am trying to add a context menu on SWT Table with the Key Name. Context Menu is coming properly but I am not able to set the key name as we can mention as a "sequence" in Menu Contribution. I am not using Menu Contribution but using a MenuItem.

Here is my code.

final MenuItem item = new MenuItem(menu, SWT.PUSH);   
item.setText(save);
item.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            //saveFunction
        }
 });

This is working but I want to add the Key name also with the name of Menu something like this:

enter image description here

Can anyone please help me as I can not use MenuContribution.


Solution

  • You can use MenuItem.setAccelerator to set the key for the menu item:

    item.setAccelerator(SWT.MOD1 | 'S');
    

    Note that this is only active when the menu is shown, if the menu is not shown you would need to use a key listener. I have used the SWT.MOD1 modifier here rather than SWT.CTRL so that the key will be the correct ⌘+S on macOS.

    On platforms that don't automatically add the accelerator text you can get set the text using:

    String acceleratorText = Action.convertAccelerator(SWT.MOD1 | 'S');
    
    item.setText(save + '\t' + acceleratorText);
    

    Here Action is org.eclipse.jface.action.Action.

    In an Eclipse plug-in you should probably be using a retargetable action to integrate with the standard save code.