如何在SWT中禁用系统托盘图标上下文菜单?

时间:2012-08-05 12:10:00

标签: java menu swt contextmenu system-tray

我有托盘图标,我已经附加了一个菜单,以便当用户右键单击它时,它会弹出。

在我的应用程序中,我想禁用显示的内容菜单,稍后再重新启用它。我是怎么做到的我无法找到一个例子,而mnuPopup.setEnabled(false)似乎无法正常工作。

以下是创建托盘图标并将菜单附加到其上的代码片段。

Tray trySysTray = display.getSystemTray();
Menu mnuPopup = new Menu(shell, SWT.POP_UP);
TrayItem itmTrayItem = new TrayItem(trySysTray, SWT.NONE);

itmTrayItem.addListener(SWT.MenuDetect, new Listener() {
    public void handleEvent(Event event) {
        mnuPopup.setVisible(true);
    }
});

1 个答案:

答案 0 :(得分:1)

以下应该做的工作:

public class MiniExample {
    // the boolean to decide if menu is shown
    private static boolean showMenu = true;

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

        Tray tray = display.getSystemTray();
        final TrayItem item = new TrayItem(tray, SWT.NONE);

        // INPUT A REAL IMAGE HERE!
        item.setImage(SOME_IMAGE);

        item.addMenuDetectListener(new MenuDetectListener() {

            @Override
            public void menuDetected(MenuDetectEvent event) {
            // if menu shall not be shown, tell it to the event
                if(!showMenu)
                {
                    event.doit = false;
                    return;
                }

            // else create the menu
                Menu menu = new Menu(shell, SWT.POP_UP);
                MenuItem menuitem = new MenuItem(menu, SWT.PUSH);
                menuitem.setText("Do Something");
                menuitem.addListener(SWT.Selection, new Listener() {
                    public void handleEvent(Event e) {
                        System.out.println("Do something!");
                    }
                });

                menu.setVisible(true);
                while (!menu.isDisposed() && menu.isVisible()) {
                    if (!shell.getDisplay().readAndDispatch())
                        shell.getDisplay().sleep();
                }

            // remember to dispose it !!
                menu.dispose();
            }
        });

        Button button = new Button(shell, SWT.PUSH);
        button.setText("Button");
        button.addSelectionListener(new SelectionListener() {

            @Override
            public void widgetSelected(SelectionEvent arg0) {
                // button decides if menu is shown or not
                showMenu = !showMenu;
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent arg0) {

            }
        });

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