Close

PrimeFaces - MegaMenu Example

[Last Updated: Jul 7, 2017]

In this example, we will learn how to build a dropdown MegaMenu programmatically. The main difference between MenuBar and MegaMenu is that: MeuBar arranges sub-menus/items directly to parent menu, whereas, MegaBar arranges items in columns. That means, in MegaMenu, we can group related items together in columns and add all columns to a one single root parent. Let's understand that with an example.

JSF page

src/main/webapp/index.xhtml

<h:body>
    <h2>PrimeFaces MegaMenu Example</h2>
    <p:megaMenu model="#{menuBean.menuModel}">
    </p:megaMenu>
</h:body>

The manage bean

@ManagedBean
@ViewScoped
public class MenuBean {
  private MenuModel model;
  private DefaultSubMenu rootMenu;

  @PostConstruct
  public void init() {
      model = new DefaultMenuModel();
      rootMenu = new DefaultSubMenu("Menu");
      model.addElement(rootMenu);
      addMenu("File", "New", "Open", "Close", "Exit");
      addMenu("Edit", "Undo", "Redo", "Cut", "Copy");
      addMenu("View", "Summary", "Settings", "Layout");
      addMenu("Help", "Help topics", "Support");
  }


  public void addMenu(String label, String... items) {

      DefaultMenuColumn column = new DefaultMenuColumn();

      //a submenu inside column
      DefaultSubMenu theColumnMenu = new DefaultSubMenu(label);
      column.addElement(theColumnMenu);

      for (Object item : items) {
          DefaultMenuItem mi = new DefaultMenuItem(item);
          mi.setUrl("#");
          theColumnMenu.addElement(mi);
      }
      //the main menu has columns instead of items
      rootMenu.addElement(column);
  }

  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 MenuMenu Example Project Select All Download
  • mega-menu-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MenuBean.java
          • webapp

    Nested Columns in MegaMenu

    In above project example, MenuBean2 tries to add nested mega columns but that doesn't work. It looks like adding nested sub menu to columns is not supported for MegaMenu.

    See Also