Adding Drop-Down Menus

Executing MenuShell won’t display a menu system because no high-level menus have been created and added to the menu bar. To do that, you need to create instances of the MenuItem class using the SWT.CASCADE style.

How do I do that?

Create an instance of the MenuItem class for each desired drop down and set the text attribute of each such instance to represent the clickable text the user will see. These instances of MenuItem are what the user will see running across the menu bar (e.g., File). Instances of MenuItem are attached directly to the menu bar by passing a reference to the menu bar in the MenuItem constructor. These MenuItem objects must be given the SWT.CASCADE style. The setText( ) method is called to specify the text you wish to appear on the menu:

MenuItem file = new MenuItem(m, SWT.CASCADE);
file.setText("File");

Next, create a Menu instance to attach to the cascading menu item. This instance of Menu is the container for the individual menu items that appear when the user clicks the cascading menu (i.e., when the menu drops down). This time you pass the Menu constructor the SWT.DROP_DOWN style in addition to a reference to the containing Shell:

Menu filemenu = new Menu(s, SWT.DROP_DOWN);
file.setMenu(filemenu);

Finally, create instances of MenuItem to add to the DROP_DOWN style menu, passing them a reference to the containing Menu instance and specifying the SWT.PUSH style (one of the other available MenuItem styles):

MenuItem openItem = new MenuItem(filemenu, ...

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.