9.8. Creating Text Menu Items

Problem

You want to add menu items that display text captions to a menu and handle selection events for those items.

Solution

Use the MenuItem class and the SelectionAdapter class. Create a MenuItem object, use the addSelectionListener method to add a listener to it, and use the setText method to set the text caption in the menu item.

Discussion

To implement a File Save item to the menu example we started in the previous recipe, create a new MenuItem object with the caption Save, pass the fileMenu object to its constructor, and give this item the style SWT.PUSH:

public MenuClass( )
     .
     .
     .
    menuBar = new Menu(shell, SWT.BAR);
    fileMenuHeader = new MenuItem(menuBar, SWT.CASCADE);
    fileMenuHeader.setText("&File");

    fileMenu = new Menu(shell, SWT.DROP_DOWN);
    fileMenuHeader.setMenu(fileMenu);

    fileSaveItem = new MenuItem(fileMenu, SWT.PUSH);
               fileSaveItem.setText("&Save");
     .
     .
     .

To make this menu item active, connect it to a selection listener class we’ll name MenuListener:

fileSaveItem.addSelectionListener(new MenuItemListener( ));

The MenuListener class will extend the SelectionAdapter class. As mentioned in Chapter 8, all SWT listener interfaces have adapter classes with stub implementations of all the interface’s methods; if you extend an adapter class, you have to implement only the methods you want to override. In this case, we’ll display the text of the selected item by retrieving the menu item widget that caused the event; note that if the selected item was File ...

Get Eclipse Cookbook 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.