在iReport 3.7.6中,您只需选中BarPlot属性下的“显示标签”框.
在先前版本(3.1.4)中,我必须创建ChartCustomizer类.
如果您需要格式化标签中的数字(例如,为百分比,添加千位分隔符等),那么您肯定需要ChartCustomizer,即使在新版本中也是如此.
一个简单的例子:
import java.text.NumberFormat;
import net.sf.jasperreports.engine.JRChart;
import net.sf.jasperreports.engine.JRChartCustomizer;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.AbstractCategoryItemLabelGenerator;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
public class SimpleBarChartCustomizer implements JRChartCustomizer {
public void customize(JFreeChart chart, JRChart jasperChart) {
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
CategoryItemRenderer catRenderer = ((CategoryItemRenderer)renderer);
catRenderer.setBaseItemLabelGenerator(new NumberLabelGenerator("", NumberFormat.getInstance()));
}
static class NumberLabelGenerator extends AbstractCategoryItemLabelGenerator implements CategoryItemLabelGenerator {
public NumberLabelGenerator(String labelFormat,
NumberFormat formatter, NumberFormat percentFormatter) {
super(labelFormat, formatter, percentFormatter);
}
protected NumberLabelGenerator(String labelFormat, NumberFormat formatter) {
super(labelFormat, formatter);
}
private NumberFormat formatter = NumberFormat.getInstance();
public String generateLabel(CategoryDataset dataset, int series, int category) {
Number b = dataset.getValue(series, category);
formatter.setMaximumFractionDigits(2);
return formatter.format(b);
}
}
}