Interactive JSF Charts

So far I’ve posted two entries about PrimeFaces chart components, one is introductory and secone one is about chart polling to display live data. This entry is about interactivity. When a series item is clicked, chart components do an ajax call and queues an ItemSelectEvent and by using a itemSelectListener you can listen chart events. Here’s an example;

<p:pieChart value="#{chartBean.sales}" var="sale" categoryField="#{sale.brand}" dataField="#{sale.amount}"
            itemSelectListener="# {chartBean.itemSelect}" update="info"
            styleClass="pie" style="chartStyle"/>

<h: outputText id="info" value="#{chartBean.message}" />

itemSelectListener is the important part, it’s a methodexpression that’s invoked when an item on chart is clicked. An org.primefaces.ui.event.chart.ItemSelectEvent is passed to the itemSelectListener, itemSelectEvent contains useful information about the selected item.

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.primefaces.examples.domain.Birth;
import org.primefaces.examples.domain.Vote;
import org.primefaces.optimus.config.Scope;
import org.primefaces.optimus.config.annotations.Controller;
import org.primefaces.ui.event.chart.ItemSelectEvent;

@Controller(name="chartBean", scope=Scope.VIEW)
public class ChartBean implements Serializable {

    private List<Sale> sales;

    private String message;

    public ChartBean() {
        sales = new ArrayList<Sale>();
        sales.add(new Sale("Brand 1", 540));
        sales.add(new Sale("Brand 2", 325));
        sales.add(new Sale("Brand 3", 702));
        sales.add(new Sale("Brand 4", 421));
    }

    public List<Sale> getSales() {
        return sales;
    }

    public void itemSelect(ItemSelectEvent event) {
        message = "Item Index: " + event.getItemIndex() + ", Series Index:" + event.getSeriesIndex();
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Finally, chart uses PrimeFaces Partial Page Rendering, the components provided with the update
attribute is partially updated after the ajax response, in this case, the outputText.

Online Demo
The example I’ve given given here, can be seen in action at online demo of PrimeFaces.

Comments are closed.

%d bloggers like this: