package com.wkx.jfreechart; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.util.Random; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.title.LegendTitle; import org.jfree.chart.title.TextTitle; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class MyBarChartTest extends ApplicationFrame { public MyBarChartTest(String title) { super(title); JFreeChart barChart = createBarChart(createDateset()); JPanel localPanel = new ChartPanel(barChart); localPanel.setPreferredSize(new Dimension(500,270)); setContentPane(localPanel); } private String[] city={"北京","上海","深圳","西安","广州"}; private String[] fruit={"苹果","鸭梨","桔子","香蕉","栗子"}; public static void main(String[] args) { MyBarChartTest barChartTest = new MyBarChartTest("柱形图测试"); barChartTest.pack(); RefineryUtilities.centerFrameOnScreen(barChartTest); barChartTest.setVisible(true); } public CategoryDataset createDateset(){ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Random r = new Random(); for(int i=0;i<city.length;i++){ for(int j=0;j<fruit.length;j++){ dataset.setValue(r.nextDouble() * 10, city[i], fruit[j]); } } return dataset; } public JFreeChart createBarChart(CategoryDataset dataset){ JFreeChart barChart = ChartFactory.createBarChart("柱状图测试", "水果", "产量", dataset, PlotOrientation.VERTICAL, true, true, true); //获取绘图区 CategoryPlot plot = barChart.getCategoryPlot(); //设置绘图区网格线是否可见(竖着的网格线) plot.setDomainGridlinesVisible(true); //设置绘图区网格线颜色(竖着的网格线) plot.setDomainGridlinePaint(Color.RED); //设置绘图区网格交叉线是否可见(单击时出现的横线) plot.setRangeCrosshairVisible(true); //设置绘图区网格交叉线颜色(单击时出现的横线) plot.setRangeCrosshairPaint(Color.BLUE); //数据轴网格线条颜色(横着的线条) plot.setRangeGridlinePaint(Color.GRAY); //数据轴网格线条样式粗细(横着的线条) plot.setRangeGridlineStroke(new BasicStroke(1.0F)); //获取标题对象 TextTitle title = barChart.getTitle(); //设置标题字体 title.setFont(new Font("黑体", Font.PLAIN, 20)); //获取底部对象 LegendTitle legend = barChart.getLegend(); //设置底部字体 legend.setItemFont(new Font("宋体", Font.PLAIN, 14)); //设置绘图区背景色 barChart.setBackgroundPaint(Color.PINK); //数据区的分类轴 CategoryAxis domainAxis = plot.getDomainAxis(); //坐标轴标题字体 domainAxis.setLabelFont(new Font("黑体", Font.PLAIN, 16)); //坐标轴标尺值字体 domainAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 16)); //数据区的数据轴 NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis(); //坐标轴标题字体 numberAxis.setLabelFont(new Font("黑体", Font.PLAIN, 16)); //坐标轴标尺值字体 numberAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 16)); return barChart; } }