This example shows how to use PrimeFaces HotKey binding with ajax calls.
Example
In this example, we are going to navigate server side List by binding left/right keys on the client side.
JSF page
src/main/webapp/index.xhtml<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h2>PrimeFaces - HotKey Example</h2>
<h:form>
<p:hotkey bind="left"
actionListener="#{itemsBean.selectPreviousItem}"
update="itemDisplay"
onstart="showKey('LEFT')"/>
<p:hotkey bind="right"
actionListener="#{itemsBean.selectNextItem}"
update="itemDisplay"
onstart="showKey('RIGHT')"/>
<h:outputText id="itemDisplay" value="#{itemsBean.item}"/>
<br/>
</h:form>
<br/>
<div id="keyDiv"></div>
<script type="text/javascript">
function showKey(direction){
$("#keyDiv").stop().html(direction).fadeIn(10).fadeOut(400);
}
</script>
</h:body>
</html>
In above page, we are also displaying what key is pressed by calling local JavaScript function before Ajax call is dispatched (via 'onstart' attribute).
Managed Bean
@ManagedBean
@ViewScoped
public class ItemsBean {
private List<String> items = Arrays
.asList("1) Malevolence Statuette", "2) Tranquility Fruit", "3) Impurity Urn", "4) Grave Gem",
"5) Domination Door", "6) Seal of Valor", "7) Seal of Venom", "8) Robes of Spite");
private int index = -1;
public void selectPreviousItem(ActionEvent ae) {
//circular navigation
index = index == -1 || index == 0 ? items.size() - 1 : index - 1;
}
public void selectNextItem(ActionEvent ae) {
//circular navigation
index = index == items.size() - 1 ? 0 : index + 1;
}
public String getItem() {
return index == -1 ? "" : items.get(index);
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
On pressing left or right key:
Example ProjectDependencies and Technologies Used: - primefaces 6.2:
PrimeFaces is one of the most popular UI libraries in Java EE Ecosystem and widely used by software companies, world renowned brands, banks, financial institutions, insurance companies, universities and more.
[Description from primefaces-6.2.pom]
- 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
|