简体   繁体   中英

Java, swt, How to distinguish right-click from left-click on popup menu

How can I distinguish right-click from left-click on popup menu in swt?

By adding a SelectionListener I can act on both left and right-click, but how do I know which one was used? Is it possible to have a MouseListener on a MenuItem?

What I want to do is similar to a browser-favorites menu, left-click to select and right-click for a favorite context menu.

Button bn = new Button(shell, SWT.FLAT);
bn.setText("Right Click to see the popup menu");

Menu popupMenu = new Menu(bn);
MenuItem newItem = new MenuItem(popupMenu, SWT.CASCADE);
newItem.setText("New");

newItem.addSelectionListener(new SelectionListener() {
 public void widgetSelected(SelectionEvent e) {    
      System.out.print("SELECTED1\n" );
 }
 public void widgetDefaultSelected(SelectionEvent e) {
      System.out.print("SELECTED2\n" );
 }
});

To clarify: Sorry, did not manage to include a screen shot, but I think you can see what I mean if you follow this description.

  1. Select the Favorites menu in Windows Explorer (or probably any other browser)
  2. If you left-click on one of your favorites the browser will open this URL, but you may also Right-click on this favorite.
  3. Right-click will bring up a context menu valid for the selected favorite.

I also need two different actions for the same MenuItem (actually for the same purpose as the browser).

You can listen for SWT.Selection for the left click and SWT.MenuDetect for the right click:

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell();
    shell.setText("StackOverflow");
    shell.setLayout(new FillLayout());

    Button bn = new Button(shell, SWT.FLAT);
    bn.setText("Right Click to see the popup menu");

    Menu popupMenu = new Menu(bn);
    MenuItem newItem = new MenuItem(popupMenu, SWT.CASCADE);
    newItem.setText("New");

    bn.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            System.out.println("click");
        }
    });
    bn.addListener(SWT.MenuDetect, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            System.out.println("menu");
        }
    });
    bn.setMenu(popupMenu);

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();
}

That said, for the menu you don't need the SWT.MenuDetect listener. Just calling Button#setMenu(Menu) does the job just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM