例1、生成报表。
第一步、sql.sql
SELECT cdsort,COUNT(*) FROM cdinfo GROUP BY cdsort
第二步、
package cn.itcast.demo;
/* * 创建一个柱状图 */
public class BarDemo {
public static void main(String[] args) {
//1.创建JFreeChart图表
CategoryDataset dataset=getDataset();
JFreeChart chart=ChartFactory.createBarChart3D("cd类别和数量对照表",//图表的主标题
"cd类别",//x轴的名称 :等级轴
"数量", //y轴的名称:值轴
dataset, //图表需要的数据(数据集)
PlotOrientation.VERTICAL,//图表中柱状图的方向
true,//是否显示图例 (轴上的刻度)
true, //是否显示工具的提示,
true);//是否产生url连接
//1.2获取图形的绘制结构(图表)
CategoryPlot categoryPlot=(CategoryPlot) chart.getPlot();
//1.3获取x轴
//System.out.println(categoryPlot.getDomainAxis());可以看到getDomainAxis()的返回类型
CategoryAxis3D categoryAxis3D=(CategoryAxis3D) categoryPlot.getDomainAxis();
//1.4获取y轴
NumberAxis3D numberAxis3D=(NumberAxis3D)categoryPlot.getRangeAxis();
//1.5获取Renderer对象(图形的绘制单元----绘图域)
BarRenderer3D barRenderer3D=(BarRenderer3D) categoryPlot.getRenderer();
//2.处理乱码
//2.1处理主标题乱码
chart.getTitle().setFont(new Font("黑体",Font.BOLD,18));
//2.2处理子标题乱码
chart.getLegend().setItemFont(new Font("黑体",Font.BOLD,16));
//2.3.1处理x轴名称乱码
categoryAxis3D.setLabelFont(new Font("宋体",Font.BOLD,15));
//2.3.2处理x轴上乱码
categoryAxis3D.setTickLabelFont(new Font("宋体",Font.BOLD,15));
//2.4.1处理x轴名称乱码
numberAxis3D.setLabelFont(new Font("宋体",Font.BOLD,15));
//2.4.2处理y轴上乱码
numberAxis3D.setTickLabelFont(new Font("宋体",Font.BOLD,15));
//3.设置y轴的刻度(将刻度每个单元格设置为2)
numberAxis3D.setAutoTickUnitSelection(false);//将y轴的单元格设置为手动
NumberTickUnit numberTickUnit=new NumberTickUnit(2);
numberAxis3D.setTickUnit(numberTickUnit);
//4.设置柱状上面的数字
barRenderer3D.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
//4.2设置数子可见
barRenderer3D.setBaseItemLabelsVisible(true);
//4.3设置柱状图上的字体
barRenderer3D.setBaseItemLabelFont(new Font("黑体",Font.BOLD,15));
//4.4设置柱状图的宽度
barRenderer3D.setMaximumBarWidth(0.08);//百分数
//5.保存成jpeg格式
File file=new File("D:\\fandong.jpg");
try {
ChartUtilities.saveChartAsJPEG(file, chart,600,400);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//6.在JFreame中显示图形;
ChartFrame cf=new ChartFrame("cd数量和类别",chart);
cf.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
cf.setVisible(true);
cf.pack();//自动调整框架的大小
}
/* 生成数据集 */
public static CategoryDataset getDataset(){
/*处理二维和三维的数据*/
DefaultCategoryDataset dataset=new DefaultCategoryDataset();
/* 流行 6 民乐 5 摇滚 8 京腔 1*/
dataset.addValue(6, "类别", "流行");
dataset.addValue(5, "类别", "民乐");
dataset.addValue(8, "类别", "摇滚");
dataset.addValue(1, "类别", "京腔");
return dataset;
}
}