javamenuclickswtmouseleftbuttondown

How to display a popup menu by mouse left click in swt?


How to display a popup menu by mouse left click? I know the default is for mouse right click. But I want to expand(display) the menu just by a normal selection of a button. (by normal left click). How to popup a popup menu by normal right click is as follows.

final Button btnNewgroup = new Button(compositeTextClient, SWT.NONE);
Menu menu = new Menu(btnNewgroup);
btnNewgroup.setMenu(menu);
MenuItem mntmNewItem = new MenuItem(menu, SWT.NONE);
mntmNewItem.setText("New Item");
MenuItem mntmNewItem2 = new MenuItem(menu, SWT.NONE);
mntmNewItem2.setText("New Item2");

Solution

  • Use a selection listener on the button:

    btnNewgroup.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(final SelectionEvent e)
      {
        Rectangle bounds = btnNewgroup.getBounds();
    
        Point point = btnNewgroup.getParent().toDisplay(bounds.x, bounds.y + bounds.height);
    
        menu.setLocation(point);
    
        menu.setVisible(true);
      }
    });