There are very few Java-only (no XML) JasperReport examples out there. I am attempting to create a simple pie chart programmatically (in Java) and am getting stuck in some of the implementation.
Please note: I have been using iReport Designer for several days now in order to udnerstand the auto-generated JRXML that gets generated, and now believe I have pie chart JRXML pretty well understood. But I need a pure Java implementation here, one that uses no XML at all. So using the JRXmlLoader
isn't an option either, partially because I just want to learn the Java API.
Let me begin by stating that I will be feeding the pie chart from a JRBeanArrayDataSource
that uses my own PieSlice
POJOs:
public class PieSlice
{
private String label;
private Double value;
public PieSlice()
{
this("", -1);
}
public PieSlice(String lbl, Double val)
{
setLabel(lbl);
setValue(val);
}
public String getLabel()
{
return label;
}
public String getValue()
{
return value;
}
}
I will then create a factory for the data source and feed it to the JasperFillManager
as follows:
public class PieSliceFactory
{
private static String[] slices =
{
new PieSlice("Fizz", 75.0),
new PieSlice("Buzz", 25.0);
};
public static getSlices()
{
return ArrayList.asList(slices);
}
}
JasperReport jasperReport = JasperFillManager.fillReport(jasperDesign, new JRBeanArrayDataSource(PieSliceFactory.getSlices()));
This should fill the report's pie chart with 2 slices. I am struggling with the JasperDesign object. Normally, the JRXML to support this would look like:
<pieDataset>
<keyExpression><![CDATA[$F{PieSlice}.label]]></keyExpression>
<valueExpression><![CDATA[$F{PieSlice}.weight]]></valueExpression>
</pieDataset>
Thus for every record (bean) returned by the datasource (in this case 2), that record's "label" property is fed into the pie chart as the current slice's category/key, and that record's "value" is fed into the chart as the current slice's value.
My problem is that the Java JasperDesign
API doesn't seem to support this (at least to a newbie). I would expect to see the API capable of something along the following lines:
JRDesignChart piechart = new JRDesignChart();
JRDesignChartDataset pieDataset = new JRDesignChartDataset();
JRExpression pieLabelExrepssion, pieValueExpression;
pieLabelExpression = new JRExpression(java.lang.String, "$F{PieSlice}.label");
pieValueExpression = new JRExpression(java.lang.Double, "$F{PieSlice}.value");
pieDataset.setKeyExpression(pieLabelExpression);
pieDataset.setValueExpression(pieValueExpression();
piechart.addDataset(pieDataset);
But to my suprise, JRDesignChartDataset
does not have methods/properties for the <keyExpression>
and <valueExpression>
tags present in JRXML.
How can I accomplish this? What JRDesign
classes/methods should I be using to map my PieSlice
properties (label
& value
) to the <pieDataset>
key/value expressions?
Thanks in advance for any and all help.