Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing a right click menu for a SWT TableItem?

Tags:

java

swt

Is it possible to show a right click menu on table items with SWT? The menu would be different for every item, e.g for some rows, some of the menu items would be enabled, for others, they would be disabled. So, each row would need its own menu, and when setting up the menu i'd need a way to identify which row I was working with.

Any ideas?

like image 230
user2790209 Avatar asked Jan 13 '23 07:01

user2790209


2 Answers

Listening for SWT.MouseDown, as suggested by @user4793956, is completely useless. The context menu is always brought up, no need to call setVisible(true). Quite contrary, you need to cancel the SWT.MenuDetect event, if you do not want the menu to pop up.

This works for me:

// Create context menu
Menu menuTable = new Menu(table);
table.setMenu(menuTable);

// Create menu item
MenuItem miTest = new MenuItem(menuTable, SWT.NONE);
miTest.setText("Test Item");

// Do not show menu, when no item is selected
table.addListener(SWT.MenuDetect, new Listener() {
  @Override
  public void handleEvent(Event event) {
    if (table.getSelectionCount() <= 0) {
      event.doit = false;
    }
  }
});
like image 114
user1438038 Avatar answered Jan 27 '23 22:01

user1438038


Without using a DynamicTable:

    Menu contextMenu = new Menu(table);
    table.setMenu(contextMenu);
    MenuItem mItem1 = new MenuItem(contextMenu, SWT.None);
    mItem1.setText("Menu Item Test.");

    table.addListener(SWT.MouseDown, new Listener(){

        @Override
        public void handleEvent(Event event) {
            TableItem[] selection = table.getSelection();
            if(selection.length!=0 && (event.button == 3)){
                contextMenu.setVisible(true);
            }

        }

    });
like image 30
user4793956 Avatar answered Jan 28 '23 00:01

user4793956