Close

PrimeFaces - MenuBar Example

[Last Updated: Jul 5, 2017]

In this example, we will learn how to build a dropdown menu programmatically with PrimeFace's MenuModel and menubar tag.

JSF page

src/main/webapp/index.xhtml

<h:body style="margin:50px;">
    <h2>PrimeFaces MenuBar Example</h2>
    <p:menubar model="#{menuBean.menuModel}">
    </p:menubar>
</h:body>

The manage bean

@ManagedBean
@ViewScoped
public class MenuBean {
  private MenuModel model = new DefaultMenuModel();

  @PostConstruct
  public void init() {
      addMenu("File", "New", "Open", "Close", "Exit");
      addMenu("Edit", "Undo", "Redo", "Cut", "Copy");
      addMenu(addMenu("View", "Summary"), "Tools", "Settings", "Layout");
      addMenu("Help", "Help topics", "Support");
  }

  public DefaultSubMenu addMenu(String label, String... items) {
      return addMenu(null, label, items);
  }

  public DefaultSubMenu addMenu(DefaultSubMenu parentMenu,
                                String label, String... items) {
      DefaultSubMenu theMenu = new DefaultSubMenu(label);
      for (Object item : items) {
          DefaultMenuItem mi = new DefaultMenuItem(item);
          mi.setUrl("#");
          theMenu.addElement(mi);
      }
      if (parentMenu == null) {
          model.addElement(theMenu);
      } else {
          parentMenu.addElement(theMenu);
      }
      return theMenu;
  }

  public MenuModel getMenuModel() {
      return model;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

Dropdown MenuBar Example Select All Download
  • menu-bar-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MenuBean.java
          • webapp

    See Also