2011年12月2日 星期五

SWT now supports Mac Application Menu (About, Preferences, and Quit)


Hooking Mac's application menu is no longer a trouble issue for SWT (standard widget toolkits) developers.  Display.getSystemMenu() is a new API returns the system-provided menu for the application.  All you have to do is comparing a MenuItem's id with various SWT.ID_* constants.  You can even change default system MenuItem's name.

  • SWT.ID_QUIT
  • SWT.ID_HIDE
  • SWT.ID_HIDE_OTHERS
  • SWT.ID_PREFERENCES
  • SWT.ID_ABOUT

Display.getSystemMenu() returns null if not running on Mac OS X.  Here's a sample usage:

Menu systemMenu = Display.getDefault().getSystemMenu();
if (systemMenu != null) {
    MenuItem sysItem = getSystemItem(systemMenu, SWT.ID_PREFERENCES);
    sysItem.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            System.out.println("Preferences");
        }
    });
    sysItem.setText("My Preferences");
}

You need a getSystemItem() function to make above code work.

static MenuItem getSystemItem(Menu menu, int id) {
    for (MenuItem item : menu.getItems()) {
        if (item.getID() == id) return item;
    }
    return null;
}

That's all.  Check SWT snippet354 for a detailed example of how you can use this API in a cross-platform application.  It's much easier than my previous way hooking application menu by CocoaUIEnhancer.

沒有留言 :

張貼留言

Related Posts Plugin for WordPress, Blogger...