Поиск по сайту:

Пример меню Primefaces, MenuBar, MenuButton, TieredMenu, SlideMenu


Основная цель этого руководства — охватить компоненты главного меню, которые используются при реализации Primefaces. Как правило, огромное количество приложений, разбросанных по Интернету, используют другую форму меню. В этом руководстве будут рассмотрены следующие типы меню:

  • Меню: компонент навигации с подменю и пунктами меню.
  • MenuBar: компонент горизонтальной навигации.
  • MenuButton: используется для отображения различных команд во всплывающем меню.
  • TieredMenu: используется для отображения вложенных подменю с наложениями.
  • SlideMenu: используется для отображения вложенных подменю с скользящей анимацией.

Давайте начнем объяснять все эти типы меню, чтобы увидеть все те функции, которые Primefaces предоставляет для этого типа компонентов.

Меню Primefaces — основная информация

Tag menu
Component Class org.primefaces.component.menu.Menu
Component Type org.primefaces.component.Menu
Component Family org.primefaces.component
Renderer Type org.primefaces.component.MenuRenderer
Renderer Class org.primefaces.component.menu.MenuRenderer

Меню Primefaces - Атрибуты

Name Default Type Description
id null String Unique identifier of the component.
rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered.
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean.
widgetVar null String Name of the client side widget.
model null MenuModel A menu model instance to create menu programmatically.
trigger null String Target component to attach the overlay menu.
my null String Corner of menu to align with trigger element.
at null String Corner of trigger to align with menu element.
overlay false Boolean Defines positioning type of menu, either static or overlay.
style null String Inline style of the main container element.
styleClass null String Style class of the main container element.
triggerEvent click String Event to show the dynamic positioned menu.

Меню Primefaces — Начало работы

Меню состоит из подменю и пунктов меню. Подменю используются для группировки пунктов меню, в то время как пункты меню соответствуют тем действиям, которые требуются. В следующем примере показано самое простое использование компонента меню. index.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form>
	<p:menu>
		<p:submenu label="File">
			<p:menuitem value="Open"></p:menuitem>
			<p:menuitem value="Edit"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Exit"></p:menuitem>
		</p:submenu>
		<p:submenu label="Help">
			<p:menuitem value="About Primefaces"></p:menuitem>
			<p:menuitem value="Contact Us"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Help"></p:menuitem>
		</p:submenu>
	</p:menu>
</h:form>
</html>

Меню Primefaces - Меню наложения

Меню можно расположить двумя способами; статический или динамический. Статическое положение означает, что меню находится в обычном потоке страниц. Напротив, динамические меню не находятся в обычном потоке страницы, что позволяет им накладываться на другие элементы. Для динамического определения меню вы должны выполнить следующие шаги:

  • Определите свое меню обычным образом, задав для атрибута наложения значение true и связав атрибут триггера меню с идентификатором инициированного действия.
  • Настройте оба атрибута my и at menu, чтобы указать угол меню для выравнивания с элементом триггера и угол триггера для выравнивания с элементом меню соответственно.
  • Пары левый, правый, нижний и верхний – единственные допустимые значения для атрибутов my и at.

index1.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form>
	<p:menu overlay="true" trigger="triggerButton" my="left top" at="right top">
		<p:submenu label="File">
			<p:menuitem value="Open"></p:menuitem>
			<p:menuitem value="Edit"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Exit"></p:menuitem>
		</p:submenu>
		<p:submenu label="Help">
			<p:menuitem value="About Primefaces"></p:menuitem>
			<p:menuitem value="Contact Us"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Help"></p:menuitem>
		</p:submenu>
	</p:menu>
	<p:commandButton id="triggerButton" value="Trigger Menu"></p:commandButton>
</h:form>
</html>

  • После активации действия триггерного меню отображается заданное вами меню.

Меню Primefaces — Ajax и не-Ajax действия

Как и сейчас, вы разработали простое статическое меню и более сложное динамическое. Оба этих меню содержат элементы меню, соответствующие требуемым действиям, которые призвано предоставить меню. Эти элементы меню на самом деле являются действиями, как и p:commandButton, поэтому вы также можете применить к ним ajax. index2.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form>
	<p:growl id="message"></p:growl>
	<p:menu overlay="true" trigger="triggerButton" my="left top" at="right top">
		<p:submenu label="File">
			<p:menuitem value="Open" action="#{menuManagedBean.openAction}" update="message"></p:menuitem>
			<p:menuitem value="Edit"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Exit"></p:menuitem>
		</p:submenu>
		<p:submenu label="Help">
			<p:menuitem value="About Primefaces"></p:menuitem>
			<p:menuitem value="Contact Us"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Help"></p:menuitem>
		</p:submenu>
	</p:menu>
	<p:commandButton id="triggerButton" value="Trigger Menu"></p:commandButton>
</h:form>
</html>

MenuManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class MenuManagedBean {
	public String openAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Open action has activiated asynchrounsly !"));
		return "";
	}
}

Меню Primefaces - Динамические меню

Меню также можно создавать программно, это более гибко по сравнению с декларативным подходом. Вы можете определить подобное меню, используя экземпляр org.primefaces.model.MenuModel. Такие компоненты, как p:submenu, p:menuitem и p:separator, также имеют свою реализацию по умолчанию, которая используется для определения программного меню. В следующем примере показан тот же бизнес-сценарий, который вы разработали ранее, на этот раз меню будет отображаться программно. index3.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form>
	<p:growl id="message"></p:growl>
	<p:menu overlay="true" trigger="triggerButton" my="left top" at="right top" model="#{menuManagedBean.menu}">
	</p:menu>
	<p:commandButton id="triggerButton" value="Trigger Menu"></p:commandButton>
</h:form>
</html>

MenuManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSeparator;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;

@ManagedBean
@SessionScoped
public class MenuManagedBean {
	private MenuModel menu = new DefaultMenuModel();

	public MenuManagedBean(){
		// Create submenu
		DefaultSubMenu file = new DefaultSubMenu("File");
		// Create submenu
		DefaultSubMenu help = new DefaultSubMenu("Help");
		// Create menuitem
		DefaultMenuItem open = new DefaultMenuItem("Open");
		// Create menuitem
		DefaultMenuItem edit = new DefaultMenuItem("Edit");
		// Create menuitem
		DefaultMenuItem exit = new DefaultMenuItem("Exit");

		// Create menuitem
		DefaultMenuItem about = new DefaultMenuItem("About Primefaces");
		// Create menuitem
		DefaultMenuItem contact = new DefaultMenuItem("Contact Us");
		// Create menuitem
		DefaultMenuItem helpMenuItem = new DefaultMenuItem("Help");		

		// Determine menuitem action
		open.setCommand("#{menuManagedBean.openAction}");

		// Associate menuitem with submenu
		file.addElement(open);
		file.addElement(edit);
		file.addElement(new DefaultSeparator());
		file.addElement(exit);

		help.addElement(about);
		help.addElement(contact);
		help.addElement(new DefaultSeparator());
		help.addElement(helpMenuItem);

		// Associate submenu with menu
		menu.addElement(file);
		menu.addElement(help);
	}

	public MenuModel getMenu() {
		return menu;
	}

	public void setMenu(MenuModel menu) {
		this.menu = menu;
	}

	public String openAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Open action has activiated asynchrounsly !"));
		return "";
	}
}

Строка меню Primefaces — основная информация

Menubar — компонент горизонтальной навигации.

Tag Menubar
Component Class org.primefaces.component.menubar.Menubar
Component Type org.primefaces.component.Menubar
Component Family org.primefaces.component
Renderer Type org.primefaces.component.MenubarRenderer
Renderer Class org.primefaces.component.menubar.MenubarRenderer

Строка меню Primefaces — Атрибуты

Name Default Type Description
id null String Unique identifier of the component.
rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered.
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean.
widgetVar null String Name of the client side widget
model null MenuModel MenuModel instance to create menus
programmatically
style null String Inline style of menubar
styleClass null String Style class of menubar
autoDisplay false Boolean Defines whether the first level of submenus will be displayed on mouseover or not. When set to false, click event is required to display.

Строка меню Primefaces — Начало работы

Панель меню Primefaces — вложенные меню

Menubar поддерживает вложенные меню, то есть предоставляя подменю внутри другого родительского подменю. index5.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
	<p:menubar>
		<p:submenu label="File">
			<p:submenu label="Open">
				<p:menuitem value="Open Excel File"></p:menuitem>
				<p:menuitem value="Open Word File"></p:menuitem>
				<p:menuitem value="Open Power Point File"></p:menuitem>
			</p:submenu>
			<p:menuitem value="Edit"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Exit"></p:menuitem>
		</p:submenu>
		<p:submenu label="Help">
			<p:menuitem value="About JournalDev"></p:menuitem>
			<p:menuitem value="Contact Us"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Help"></p:menuitem>
		</p:submenu>
	</p:menubar>
</h:form>
</html>

Панель меню Primefaces — корневой элемент меню

Menubar также поддерживает корневой элемент меню, то есть предоставляя прямой дочерний компонент p:menuitem внутри p:menubar. index6.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
	<p:menubar>
		<p:menuitem value="Open"></p:menuitem>
	</p:menubar>
</h:form>
</html>

Панель меню Primefaces — Ajax и не-Ajax действия

Аналогично компоненту p:commandButton, p:menuitem также поддерживает действия ajaxifying. Вы уже испытали это в разделе p:menu. Вы можете использовать p:menuitem для выполнения действий (Ajax и Non-Ajax), а также для навигации. В следующем примере показано различное использование p:menuitem. index7.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
<p:growl id="message"></p:growl>
	<p:menubar>
		<p:submenu label="File">
			<p:submenu label="Open">
				<p:menuitem value="Ajax Action" action="#{menubarManagedBean.ajaxAction}" update="message"></p:menuitem>
				<p:menuitem value="Non Ajax Action" action="#{menubarManagedBean.nonAjaxAction}" ajax="false"></p:menuitem>
				<p:menuitem value="Go To JournalDev" url="https://www.journaldev.com"></p:menuitem>
			</p:submenu>
			<p:menuitem value="Edit"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Exit"></p:menuitem>
		</p:submenu>
		<p:submenu label="Help">
			<p:menuitem value="About JournalDev"></p:menuitem>
			<p:menuitem value="Contact Us"></p:menuitem>
			<p:separator/>
			<p:menuitem value="Help"></p:menuitem>
		</p:submenu>
	</p:menubar>
</h:form>
</html>

MenubarManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class MenubarManagedBean {
	public String ajaxAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
		return "";
	}

	public String nonAjaxAction(){
		return "";
	}
}

Панель меню Primefaces — динамические меню

Menubar также поддерживает его динамическое создание, вы можете создавать Menubar программно и предоставлять действия Ajax, Non-Ajax и URL, как вы это делали в разделе действий Ajax и Non-Ajax. index8.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
<p:growl id="message"></p:growl>
	<p:menubar model="#{menubarManagedBean.menubar}">
	</p:menubar>
</h:form>
</html>

MenubarManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSeparator;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;

@ManagedBean
@SessionScoped
public class MenubarManagedBean {

	private MenuModel menubar = new DefaultMenuModel();

	public MenubarManagedBean(){
		// Create submenus required
		DefaultSubMenu file = new DefaultSubMenu("File");
		DefaultSubMenu open = new DefaultSubMenu("Open");
		DefaultSubMenu help = new DefaultSubMenu("Help");

		// Create menuitems required
		DefaultMenuItem edit = new DefaultMenuItem("Edit");
		DefaultMenuItem exit = new DefaultMenuItem("Exit");

		// Create menuitems required
		DefaultMenuItem ajaxAction = new DefaultMenuItem("Ajax Action");
		ajaxAction.setUpdate("message");
		ajaxAction.setCommand("#{menubarManagedBean.ajaxAction}");

		DefaultMenuItem nonAjaxAction = new DefaultMenuItem("Non Ajax Action");
		nonAjaxAction.setAjax(false);
		nonAjaxAction.setCommand("#{menubarManagedBean.nonAjaxAction}");

		DefaultMenuItem urlAction = new DefaultMenuItem("Go To JournalDev");
		urlAction.setUrl("https://www.journaldev.com");

		DefaultMenuItem about = new DefaultMenuItem("About JournalDev");
		DefaultMenuItem contactUs = new DefaultMenuItem("Contact Us");
		DefaultMenuItem helpMenuItem = new DefaultMenuItem("Help");

		// Associate menuitems with open submenu
		open.addElement(ajaxAction);
		open.addElement(nonAjaxAction);
		open.addElement(urlAction);

		// Associate menuitems with help submenu
		help.addElement(about);
		help.addElement(contactUs);
		help.addElement(new DefaultSeparator());
		help.addElement(helpMenuItem);

		// Associate open submenu with file submenu
		file.addElement(open);
		file.addElement(edit);
		file.addElement(new DefaultSeparator());
		file.addElement(exit);

		// Associate submenus with the menubar
		this.menubar.addElement(file);
		this.menubar.addElement(help);

	}

	public MenuModel getMenubar() {
		return menubar;
	}

	public void setMenubar(MenuModel menubar) {
		this.menubar = menubar;
	}

	public String ajaxAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
		return "";
	}

	public String nonAjaxAction(){
		return "";
	}
}

Кнопка меню Primefaces — основная информация

MenuButton отображает различные команды во всплывающем меню.

Tag menuButton
Component Class org.primefaces.component.menubutton.MenuButton
Component Type org.primefaces.component.MenuButton
Component Family org.primefaces.component
Renderer Type org.primefaces.component.MenuButtonRenderer
Renderer Class org.primefaces.component.menubutton.MenuButtonRenderer

Primefaces MenuButton - Атрибуты

Name Default Type Description
id null String Unique identifier of the component.
rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered.
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean.
value null String Label of the button
style null String Style of the main container element
styleClass null String Style class of the main container element
widgetVar null String Name of the client side widget
model null MenuModel MenuModel instance to create menus programmatically
disabled false Boolean Disables or enables the button.
iconPos left String Position of the icon, valid values are left and right.
appendTo null String Appends the overlay to the element defined by search expression. Defaults to document body.

Кнопка меню Primefaces — Начало работы

MenuButton состоит из одного или нескольких пунктов меню. Те элементы меню, которые будут определены, имеют то же сходство с теми, которые уже использовались ранее, здесь также поддерживаются Ajax, не-ajax и действия навигации. index9.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
	<p:growl id="message"></p:growl>
	<p:menuButton value="MenuButton">
		<p:menuitem value="Ajax Action" action="#{menuButtonManagedBean.ajaxAction}" update="message"></p:menuitem>
		<p:menuitem value="Non Ajax Action" action="#{menuButtonManagedBean.nonAjaxAction}" ajax="false"></p:menuitem>
		<p:menuitem value="Go To JournalDev" url="https://www.journaldev.com"></p:menuitem>
	</p:menuButton>
</h:form>
</html>

MenuButtonManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSeparator;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;

@ManagedBean(name="menuButtonManagedBean")
@SessionScoped
public class MenuButtonManagedBean {
	private MenuModel menuButton = new DefaultMenuModel();

	public MenuButtonManagedBean(){

	}

	public MenuModel getMenuButton() {
		return menuButton;
	}

	public void setMenuButton(MenuModel menuButton) {
		this.menuButton = menuButton;
	}

	public String ajaxAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
		return "";
	}

	public String nonAjaxAction(){
		return "";
	}
}

Primefaces MenuButton - Динамические меню

MenuButton также может быть создан программно. Тот же самый пример MenuButton, представленный в предыдущем разделе, фактически реализован ниже с использованием программной методологии. index10.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
	<p:growl id="message"></p:growl>
	<p:menuButton value="MenuButton" model="#{menuButtonManagedBean.menuButton}">
	</p:menuButton>
</h:form>
</html>

MenuButtonManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.MenuModel;

@ManagedBean(name="menuButtonManagedBean")
@SessionScoped
public class MenuButtonManagedBean {
	private MenuModel menuButton = new DefaultMenuModel();

	public MenuButtonManagedBean(){

		// Create menuitems required
		DefaultMenuItem ajaxAction = new DefaultMenuItem("Ajax Action");
		ajaxAction.setUpdate("message");
		ajaxAction.setCommand("#{menubarManagedBean.ajaxAction}");

		DefaultMenuItem nonAjaxAction = new DefaultMenuItem("Non Ajax Action");
		nonAjaxAction.setAjax(false);
		nonAjaxAction.setCommand("#{menubarManagedBean.nonAjaxAction}");

		DefaultMenuItem urlAction = new DefaultMenuItem("Go To JournalDev");
		urlAction.setUrl("https://www.journaldev.com");

		this.menuButton.addElement(ajaxAction);
		this.menuButton.addElement(nonAjaxAction);
		this.menuButton.addElement(urlAction);

	}

	public MenuModel getMenuButton() {
		return menuButton;
	}

	public void setMenuButton(MenuModel menuButton) {
		this.menuButton = menuButton;
	}

	public String ajaxAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
		return "";
	}

	public String nonAjaxAction(){
		return "";
	}
}

Primefaces TieredMenu — основная информация

TieredMenu используется для отображения вложенных подменю с наложениями.

Tag TieredMenu
Component Class org.primefaces.component.tieredmenu.TieredMenu
Component Type org.primefaces.component.TieredMenu
Component Family org.primefaces.component
Renderer Type org.primefaces.component.TieredMenuRenderer
Renderer Class org.primefaces.component.tieredmenu.TieredMenuRenderer

Primefaces TieredMenu - Атрибуты

Name Default Type Description
id null String Unique identifier of the component
rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered.
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean
widgetVar null String Name of the client side widget.
model null MenuModel MenuModel instance for programmatic menu.
style null String Inline style of the component.
styleClass null String Style class of the component.
autoDisplay true Boolean Defines whether the first level of submenus will be displayed on mouseover or not. When set to false, click event is required to display.
trigger null String Id of the component whose triggerEvent will show the dynamic positioned menu.
my null String Corner of menu to align with trigger element.
at null String Corner of trigger to align with menu element.
overlay false Boolean Defines positioning, when enabled menu is displayed with absolute position relative to the trigger. Default is false, meaning static positioning.
triggerEvent click String Event name of trigger that will show the dynamic positioned menu.

Primefaces TieredMenu — Начало работы

TieredMenu состоит из подменю и пунктов меню, подменю могут быть вложенными, и каждое вложенное подменю будет отображаться в виде наложения. Элементы меню, задействованные в компоненте p:tieredMenu , предназначены для Ajax, не-Ajax и навигационных действий, как и все эти элементы меню, использовавшиеся ранее. В следующем примере показано самое простое применимое использование p:tieredMenu, которое содержит набор смешанных действий. index11.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
	<p:growl id="message"></p:growl>
	<p:tieredMenu>
		<p:submenu label="Ajax Menuitem">
			<p:menuitem value="Ajax Action" action="#{tieredMenuManagedBean.ajaxAction}" update="message"></p:menuitem>
		</p:submenu>
		<p:submenu label="Non Ajax Menuitem">
			<p:menuitem value="Non Ajax Action" action="#{tieredMenuManagedBean.nonAjaxAction}"></p:menuitem>
		</p:submenu>
		<p:separator/>
		<p:submenu label="Navigations">
			<p:submenu label="Primefaces links">
				<p:menuitem value="Prime" url="https://www.prime.com.tr"></p:menuitem>
				<p:menuitem value="Primefaces" url="https://www.primefaces.org"></p:menuitem>
			</p:submenu>
			<p:submenu label="Prime Blogs">
				<p:menuitem value="JournalDev" url="https://www.journaldev.com"></p:menuitem>
			</p:submenu>
		</p:submenu>
	</p:tieredMenu>
</h:form>
</html>

TieredMenuManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class TieredMenuManagedBean {
	public String ajaxAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
		return "";
	}

	public String nonAjaxAction(){
		return "";
	}
}

Многоуровневое меню Primefaces — автоотображение

Primefaces TieredMenu - Наложение

Аналогично компоненту меню, TieredMenu также можно накладывать тем же способом, который используется для наложения компонента меню (см. Наложение меню). index11.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form style="width:400px;">
	<p:growl id="message"></p:growl>
	<p:tieredMenu autoDisplay="false" trigger="triggerBtn" overlay="true" my="left top" at="right top">
		<p:submenu label="Ajax Menuitem">
			<p:menuitem value="Ajax Action" action="#{tieredMenuManagedBean.ajaxAction}" update="message"></p:menuitem>
		</p:submenu>
		<p:submenu label="Non Ajax Menuitem">
			<p:menuitem value="Non Ajax Action" action="#{tieredMenuManagedBean.nonAjaxAction}"></p:menuitem>
		</p:submenu>
		<p:separator/>
		<p:submenu label="Navigations">
			<p:submenu label="Primefaces links">
				<p:menuitem value="Prime" url="https://www.prime.com.tr"></p:menuitem>
				<p:menuitem value="Primefaces" url="https://www.primefaces.org"></p:menuitem>
			</p:submenu>
			<p:submenu label="Prime Blogs">
				<p:menuitem value="JournalDev" url="https://www.journaldev.com"></p:menuitem>
			</p:submenu>
		</p:submenu>
	</p:tieredMenu>
	<p:commandButton value="Show Menu" id="triggerBtn"></p:commandButton>
</h:form>
</html>

Primefaces TieredMenu — клиентский API

Вы также можете управлять компонентом TieredMenu с помощью клиентского API Primefaces.

Method Params Return Type Description
show() - void Shows overlay menu.
hide() - void Hides overlay menu.
align() - void Aligns overlay menu with trigger.

index11.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
	<script>
		function showMenu(){
			PF('tieredMenu').show();
		}
		function hideMenu(){
			PF('tieredMenu').hide();
		}
	</script>
</h:head>
<h:form style="width:400px;">
	<p:growl id="message"></p:growl>
	<p:tieredMenu autoDisplay="false" trigger="triggerBtn" overlay="true" my="left top" at="right top" widgetVar="tieredMenu">
		<p:submenu label="Ajax Menuitem">
			<p:menuitem value="Ajax Action" action="#{tieredMenuManagedBean.ajaxAction}" update="message"></p:menuitem>
		</p:submenu>
		<p:submenu label="Non Ajax Menuitem">
			<p:menuitem value="Non Ajax Action" action="#{tieredMenuManagedBean.nonAjaxAction}"></p:menuitem>
		</p:submenu>
		<p:separator/>
		<p:submenu label="Navigations">
			<p:submenu label="Primefaces links">
				<p:menuitem value="Prime" url="https://www.prime.com.tr"></p:menuitem>
				<p:menuitem value="Primefaces" url="https://www.primefaces.org"></p:menuitem>
			</p:submenu>
			<p:submenu label="Prime Blogs">
				<p:menuitem value="JournalDev" url="https://www.journaldev.com"></p:menuitem>
			</p:submenu>
		</p:submenu>
	</p:tieredMenu>
	<p:commandButton value="Show Menu - Normal Trigger" id="triggerBtn"></p:commandButton>
	<p:commandButton value="Show Menu - JavaScript function" onclick="showMenu()"></p:commandButton>
	<p:commandButton value="Hide Menu - JavaScript function" onclick="hideMenu()"></p:commandButton>
</h:form>
</html>

Primefaces SlideMenu — основная информация

SlideMenu используется для отображения вложенных подменю с скользящей анимацией.

Tag slideMenu
Component Class org.primefaces.component.slidemenu.SlideMenu
Component Type org.primefaces.component.SlideMenu
Component Family org.primefaces.component
Renderer Type org.primefaces.component.SlideMenuRenderer
Renderer Class org.primefaces.component.slidemenu.SlideMenuRenderer

Слайд-меню Primefaces — Атрибуты

Name Default Type Description
id null String Unique identifier of the component
rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered.
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean
widgetVar null String Name of the client side widget.
model null MenuModel MenuModel instance for programmatic menu.
style null String Inline style of the component.
styleClass null String Style class of the component.
backLabel Back String Text for back link.
trigger null String Id of the component whose triggerEvent will show the dynamic positioned menu.
my null String Corner of menu to align with trigger element.
at null String Corner of trigger to align with menu element.
overlay false Boolean Defines positioning, when enabled menu is displayed with absolute position relative to the trigger. Default is false, meaning static positioning.
triggerEvent click String Event name of trigger that will show the dynamic positioned menu.

Слайд-меню Primefaces — Начало работы — Оверлей и клиентский API

SlideMenu состоит из подменю и пунктов меню, подменю могут быть вложенными, и каждое вложенное подменю будет отображаться с анимацией слайдов. Функциональные возможности SlideMenu аналогичны функциям, определенным в многоуровневом меню, которое обсуждалось в предыдущем разделе. index12.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
	<script>
		function showMenu(){
			PF('tieredMenu').show();
		}
		function hideMenu(){
			PF('tieredMenu').hide();
		}
	</script>
</h:head>
<h:form style="width:400px;">
	<p:growl id="message"></p:growl>
	<p:slideMenu autoDisplay="false" trigger="triggerBtn" overlay="true" my="left top" at="right top" widgetVar="tieredMenu">
		<p:submenu label="Ajax Menuitem">
			<p:menuitem value="Ajax Action" action="#{slideMenuManagedBean.ajaxAction}" update="message"></p:menuitem>
		</p:submenu>
		<p:submenu label="Non Ajax Menuitem">
			<p:menuitem value="Non Ajax Action" action="#{slideMenuManagedBean.nonAjaxAction}"></p:menuitem>
		</p:submenu>
		<p:separator/>
		<p:submenu label="Navigations">
			<p:submenu label="Primefaces links">
				<p:menuitem value="Prime" url="https://www.prime.com.tr"></p:menuitem>
				<p:menuitem value="Primefaces" url="https://www.primefaces.org"></p:menuitem>
			</p:submenu>
			<p:submenu label="Prime Blogs">
				<p:menuitem value="JournalDev" url="https://www.journaldev.com"></p:menuitem>
			</p:submenu>
		</p:submenu>
	</p:slideMenu>
	<p:commandButton value="Show Menu - Normal Trigger" id="triggerBtn"></p:commandButton>
	<p:commandButton value="Show Menu - JavaScript function" onclick="showMenu()"></p:commandButton>
	<p:commandButton value="Hide Menu - JavaScript function" onclick="hideMenu()"></p:commandButton>
</h:form>
</html>

SlideMenuManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class SlideMenuManagedBean {
	public String ajaxAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ajax Update"));
		return "";
	}

	public String nonAjaxAction(){
		return "";
	}
}

Резюме

Primefaces предоставляет вам огромное количество компонентов меню пользовательского интерфейса Primefaces, которые устанавливаются разработчиком перед интересной коллекцией, из которой пользователь может выбирать. Этот учебник предназначен для разъяснения части этих типов меню. Внесите свой вклад, оставив комментарий ниже, и найдите исходный код для этого урока.

Скачать проект меню PrimeFaces