如何使用本机GWT(Java)实现上下文菜单?

时间:2014-07-24 07:50:17

标签: java gwt contextmenu

我是GWT的新人! 任何人都可以帮我实现GWT的上下文菜单吗? 我见过一些例子:

MenuBar options = new MenuBar(true);
        MenuBar gwtPopup = new MenuBar(true);
        options.addItem("GWT", gwtPopup );
        MenuItem entryPoint = new MenuItem(new SafeHtmlBuilder().appendEscaped("EntryPoint").toSafeHtml());
        entryPoint.setScheduledCommand(new ScheduledCommand()
        {
            public void execute()
            {
                Window.alert( "hello" );
            }
        } );
        final DialogBox menuWrapper = new DialogBox( true );
        menuWrapper.add( options );
        gwtPopup.addItem( entryPoint );
        Button showMenu = new Button( "Click me", new ClickHandler()
        {
            public void onClick( ClickEvent event )
            {
                menuWrapper.showRelativeTo( menuWrapper );
            }
        } );

        RootPanel.get().add( showMenu );

但它不起作用。感谢。

2 个答案:

答案 0 :(得分:2)

刚刚在博客中介绍了使用我的工作代码完成的步骤。

Context Menu or Right Click Handler in GWT

这是该代码的基本部分。

lable.sinkEvents(Event.ONCONTEXTMENU);
lable.addHandler(
    new ContextMenuHandler() {
        @Override
        public void onContextMenu(ContextMenuEvent event) {
            event.preventDefault();
            event.stopPropagation();
            popupMenu.setPopupPosition(
                event.getNativeEvent().getClientX(),
                event.getNativeEvent().getClientY());
            popupMenu.show();
        }
    }, ContextMenuEvent.getType()
);

答案 1 :(得分:0)

event.getNativeEvent()。getClientX()和event.getNativeEvent()。getClientY()在滚动页面后效果不佳。

以下是解决方案:

@Override
public void onContextMenu(ContextMenuEvent event) {
    NativeEvent nativeEvent = event.getNativeEvent();

    // stop the browser from opening the context menu
    event.preventDefault();
    event.stopPropagation();

    int x = nativeEvent.getClientX() + getScrollLeft();
    int y = nativeEvent.getClientY() + getScrollTop();

    this.contextMenu.setPopupPosition(x, y);
    this.contextMenu.show();
}

public static native int getScrollTop() /*-{
return $doc.body.scrollTop;
}-*/;

public static native int getScrollLeft() /*-{
return $doc.body.scrollLeft;
}-*/;