我在Image
上显示Canvas
。当用户右键单击画布时,将显示上下文菜单。
如果用户在图片范围内点击,我该如何才显示菜单?我可以从活动中获得x
和y
位置,但在那时肯定已经太晚了!
final Menu pixelContextMenu = new Menu(canvas);
canvas.setMenu(pixelContextMenu);
final MenuItem resetImageItem = new MenuItem(pixelContextMenu, SWT.NONE);
resetImageItem.setText("Reset Image");
resetImageItem.addListener(SWT.MenuDetect, new Listener() {
@Override
public void handleEvent(Event event) {
int x = event.x;
int y = event.y;
}
});
答案 0 :(得分:2)
如果活动位于您所在地区之外,请使用Event#doit
并将其设为false
。这是一个示例,它将显示左半部分的菜单,但不显示Canvas
的右半部分:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Stackoverflow");
shell.setLayout(new FillLayout());
final Canvas canvas = new Canvas(shell, SWT.NONE);
Menu menu = new Menu(canvas);
new MenuItem(menu, SWT.NONE).setText("MenuItem");
canvas.setMenu(menu);
canvas.addListener(SWT.MenuDetect, new Listener()
{
@Override
public void handleEvent(Event event)
{
Point location = canvas.toControl(event.x, event.y);
if(location.x > canvas.getBounds().width / 2f)
event.doit = false;
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
如果您想在任何情况下显示Menu
,但根据事件位置禁用某些菜单项,请执行以下操作:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Stackoverflow");
shell.setLayout(new FillLayout());
final Canvas canvas = new Canvas(shell, SWT.NONE);
Menu menu = new Menu(canvas);
final MenuItem item = new MenuItem(menu, SWT.NONE);
item.setText("MenuItem");
canvas.setMenu(menu);
canvas.addListener(SWT.MenuDetect, new Listener()
{
@Override
public void handleEvent(Event event)
{
Point location = canvas.toControl(event.x, event.y);
item.setEnabled(location.x <= canvas.getBounds().width / 2f);
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}