Reputation: 25
I am using Primefaces Barchart and i want to show the data in the ChartSeries when link to any bar in barchart. My code is as below:
<p:chart type="bar" model="#{dailyreport.horizontalBarChart}" rendered="#{dailyreport.chartDate != null}" style="height:900px;width:900px;" widgetVar="bchart">
</p:chart>
and the horizontalBarChart i'm setting Map for Series and the values in the map is like ("00:14",10).
I know about primefaces interactive charts But how to get that particular item data which is clicked in the chart.I managed to do the below:
public void itemSelect(ItemSelectEvent event){
Integer seriesIndex = event.getSeriesIndex();
Integer itemIndex = event.getItemIndex();
HorizontalBarChartModel cModel = (HorizontalBarChartModel) ((org.primefaces.component.chart.Chart) event.getSource()).getModel();
List<ChartSeries> cData= cModel.getSeries();
Map<Object, Number> ct = cData.get(seriesIndex).getData();
}
How to get that particular item from map using itemIndex?
Upvotes: 0
Views: 2501
Reputation: 25
i have done is like this:
HorizontalBarChartModel cModel = (HorizontalBarChartModel) ((org.primefaces.component.chart.Chart) event.getSource()).getModel();
ChartSeries mySeries = cModel.getSeries().get(event.getSeriesIndex());
Set<Entry<Object, Number>> mapValues = mySeries.getData().entrySet();
Entry<Object,Number>[] test = new Entry[mapValues.size()];
mapValues.toArray(test);
System.out.prinlnt("Key"+test[event.getItemIndex].getKey());
System.out.prinlnt("Value"+test[event.getItemIndex].getValue());
Upvotes: 2
Reputation: 12337
The problem (which is now basically a plain java one ;-)) is that the getData() on the ChartSeries is backed by a LinkedHashMap, which does not have the option to get a value based on an index (even though the LinkedHashMap is maintains the insertion order. So you have to maintain a mapping between the key and index yourself while populating the model and keep that e.g. in a bean as well. Another option to not have to do this each time is to extend the ChartSeries like this:
package some.package;
import java.util.ArrayList;
import java.util.Map;
import org.primefaces.model.chart.ChartSeries;
public class MyChartSeries extends ChartSeries {
private ArrayList<Object> indexKeyMapper = new ArrayList<>();
public void setData(Map<Object, Number> data) {
throw new RuntimeException("No, sorry");
}
public void set(Object x, Number y) {
getData().put(x, y);
indexKeyMapper.add(x);
}
public Object getKey(int index) {
return indexKeyMapper.get(index);
}
public Number getData(int index) {
return getData().get(indexKeyMapper.get(index));
}
}
And then you can use a getData(event.getItemIndex()) on the retrieved series (do not forget to cast to MyChartSeries).
(this works, I just tested)
Upvotes: 1