user2790209
user2790209

Reputation: 359

Showing a right click menu for a SWT TableItem?

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?

Upvotes: 5

Views: 12156

Answers (3)

user1438038
user1438038

Reputation: 6059

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;
    }
  }
});

Upvotes: 6

user4793956
user4793956

Reputation: 21

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);
            }

        }

    });

Upvotes: 2

user2790209
user2790209

Reputation: 359

    table = new DynamicTable(shell, SWT.BORDER | SWT.FULL_SELECTION);        
    table.addMenuDetectListener(new MenuDetectListener()
    {
        @Override
        public void menuDetected(MenuDetectEvent e)
        {                
           int index = table.getSelectionIndex();
           if (index == -1) 
             return; //no row selected

           TableItem item = table.getItem(index);
           item.getData(); //use this to identify which row was clicked.
           //The popup can now be displayed as usual using table.toDisplay(e.x, e.y)              
        }
    });

More details: http://www.eclipsezone.com/eclipse/forums/t49734.html

Upvotes: 1

Related Questions