4.12. MenuBar

The MenuBar component allows creating horizontal dropdown menus, much like the main menu in desktop applications.

// Create a menu bar
final MenuBar menubar = new MenuBar();
main.addComponent(menubar);

You insert the top-level menu items to a MenuBar object with the addItem() method. It takes a string label, an icon resource, and a command as its parameters. The icon and command are not required and can be null.

MenuBar.MenuItem beverages = menubar.addItem("Beverages", null, null);

The command is called when the user clicks the item. A menu command is a class that implements the MenuBar.Command interface.

// A feedback component
final Label selection = new Label("-");
main.addComponent(selection);

// Define a common menu command for all the menu items.
MenuBar.Command mycommand = new MenuBar.Command() {
    public void menuSelected(MenuItem selectedItem) {
        selection.setValue("Ordered a " + selectedItem.getText() + " from menu.");
    }  
};

The addItem() method returns a MenuBar.MenuItem object, which you can use to add sub-menu items. The MenuItem has an identical addItem() method.

// Put some items in the menu hierarchically
MenuBar.MenuItem beverages = menubar.addItem("Beverages", null, null);
MenuBar.MenuItem hot_beverages = beverages.addItem("Hot", null, null);
hot_beverages.addItem("Tea", null, mycommand);
hot_beverages.addItem("Coffee", null, mycommand);
MenuBar.MenuItem cold_beverages = beverages.addItem("Cold", null, null);
cold_beverages.addItem("Milk", null, mycommand);

// Another top-level item
MenuBar.MenuItem snacks = menubar.addItem("Snacks", null, null);
snacks.addItem("Weisswurst", null, mycommand);
snacks.addItem("Salami", null, mycommand);

// Yet another top-level item
MenuBar.MenuItem services = menubar.addItem("Services", null, null);
services.addItem("Car Service", null, mycommand);

The menu will look as follows:

Figure 4.25. Menu Bar

Menu Bar

CSS Style Rules

.i-menubar { }
.gwt-MenuItem {}
.gwt-MenuItem-selected {}

The menu bar has the overall style name .i-menubar. Each menu item has .gwt-MenuItem style normally and .gwt-MenuItem-selected when the item is selected.