Thursday, September 5, 2013

Primefaces Pie Chart Example

It is very easy to create charts with Primefaces. In following example you will see how to add a pie chart to your application within minutes.
☞Remember you should have Primefaces jar added in to your project before continue.
    You can download the latest version of Primefaces from below link.
    http://www.primefaces.org/downloads.html

We use <p:pieChart/> component to add the chart to out xhtml page. So our page will look like this.

<!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:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head></h:head>
<body>
    <p:pieChart title="Sales" value="#{chartBean.pieModel}" legendPosition="w"
        id="salesChart" style="width:350px;height:300px" />
</body>
</html>


Our JSF managed bean is this. Look that our getPieModel method returns a PieChartModel object. In our xhtml page the "value" attribute of <p:pieChart/> component is bound to this method.

import javax.faces.bean.ManagedBean;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "chartBean")
public class ChartBean {
    public PieChartModel getPieModel() {
PieChartModel pieModel = new PieChartModel();
        pieModel.set("Item 1", 10);
        pieModel.set("Item 2", 12.5);
        pieModel.set("Item 3", 30);
        pieModel.set("Item 4", 18);
        return pieModel;
    }
}

Now run the application and go to the page. You will get an output like below.

2 comments:

  1. What is the chart tool you used to create above pie chart. Is it an collaboration and real-time enabled tool like creately ?

    ReplyDelete
    Replies
    1. It's primefaces pie chart
      http://www.primefaces.org/showcase/ui/chart/pie.xhtml

      Delete