为什么MenuItem监听器不能在Canvas上执行?请参阅下面的测试程序。您可能希望将“Got Here”打印到控制台。
import java.util.ArrayList;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
public class MenuListenerTest {
//BufferedImage bitmapImage = null;
Image image = null;
Canvas canvas = null;
private void createContents(Shell shell) {
shell.setLayout(new FillLayout());
// Create a canvas to draw on
canvas = new Canvas(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE | SWT.DOUBLE_BUFFERED);
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;
System.out.println("Got here");
}
});
}
public static void main(String[] args)
{
new MenuListenerTest().run();
}
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window's contents
*
* @param shell the main window
*/
}
答案 0 :(得分:3)
在按下SelectionListener
时,您应使用MenuItem
拦截:
resetImageItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
System.out.println("menu item pressed");
}
});
当菜单变得可见时,会触发事件SWT.MenuDetect
。要拦截它,您必须将侦听器直接附加到Canvas
:
canvas.addListener(SWT.MenuDetect, new Listener() {
@Override
public void handleEvent(Event event) {
System.out.println("menu visible");
}
});