[英]Java, swt, How to distinguish right-click from left-click on popup menu
如何區分swt彈出菜單中的右鍵單擊和左鍵單擊?
通過添加SelectionListener,我可以在左鍵單擊和右鍵單擊上執行操作,但是我怎么知道使用了哪一個? 是否可以在MenuItem上使用MouseListener?
我要執行的操作類似於瀏覽器收藏夾菜單,單擊鼠標左鍵選擇,然后右鍵單擊收藏夾上下文菜單。
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" );
}
});
需要澄清的是:很抱歉,沒有包含屏幕截圖,但是我認為如果您遵循此描述,您會明白我的意思。
對於同一MenuItem(實際上與瀏覽器具有相同的用途),我還需要兩個不同的操作。
您可以聽SWT.Selection
作為左鍵單擊,而SWT.MenuDetect
作為右鍵單擊:
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();
}
也就是說,對於菜單,您不需要SWT.MenuDetect
偵聽器。 只需調用Button#setMenu(Menu)
完成工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.