JfreeChart本身應該是繼承Swing和awt所沿生出來的套件,所以寫法對於會寫Swing以及awt的人應該是不陌生,不外乎就是設定Jframe、Panel等等
不熟悉的人可以看一下JfreeChart所提供的原始碼並搭配JfreeChart API來學習
以下的Code某些部份是沿用範本BarChartDemo1,我刪掉用不太到的Code,所以可能會略為精簡一些
import java.awt.Color; import java.awt.Dimension; import java.awt.GradientPaint; 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.CategoryLabelPositions; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class Chart extends ApplicationFrame { private static final long serialVersionUID = 1L; public Chart(String title) { super(title); CategoryDataset dataset = createDataset(); JFreeChart chart = createChart(dataset); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setFillZoomRectangle(true); chartPanel.setMouseWheelEnabled(true); // 讓滑鼠滾輪可以放大縮小 chartPanel.setPreferredSize(new Dimension(600, 480)); setContentPane(chartPanel); } private static CategoryDataset createDataset() { String series1 = "A"; String series2 = "B"; String series3 = "C"; String category1 = "Category 1"; DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(1.0, series1, category1); dataset.addValue(7.0, series2, category1); dataset.addValue(100.0, series3, category1); return dataset; } private static JFreeChart createChart(CategoryDataset dataset) { // 建立長條圖 JFreeChart chart = ChartFactory .createBarChart("Title", "Y label", "X label", dataset, PlotOrientation.VERTICAL, true, true, false); // 設定背景顏色 chart.setBackgroundPaint(Color.white); CategoryPlot plot = (CategoryPlot) chart.getPlot(); // 設定Y軸數值 NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setDrawBarOutline(false); // 畫出長條圖 GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64)); GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0)); GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0)); renderer.setSeriesPaint(0, gp0); renderer.setSeriesPaint(1, gp1); renderer.setSeriesPaint(2, gp2); return chart; } public static void main(String[] args) { Chart chart = new Chart("Test"); chart.pack(); // 動態設定元件大小 RefineryUtilities.centerFrameOnScreen(chart); chart.setVisible(true); } }
參考資料:
http://puremonkey2010.blogspot.tw/2011/06/java-jfreechart-part-1.html
http://hsingyu-jcworld.blogspot.tw/2012/01/javajfreechart.html
http://www.jfree.org/jfreechart/api/javadoc/index.html