import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class LineCharts extends ApplicationFrame {
public LineCharts(String s) {
super(s);
setContentPane(createDemoLine());
}
public static void main(String[] args) {
LineCharts fjc = new LineCharts("折線圖");
fjc.pack();
RefineryUtilities.centerFrameOnScreen(fjc);
fjc.setVisible(true);
}
// 生成顯示圖表的面板 public static JPanel createDemoLine() {
JFreeChart jfreechart = createChart(createDataset());
saveAsFile(jfreechart, "D://testline.png", 500, 300);
return new ChartPanel(jfreechart);
}
// 生成圖表主對象JFreeChart public static JFreeChart createChart(DefaultCategoryDataset linedataset) {
//定義圖表對象
JFreeChart chart = ChartFactory.createLineChart("LineChart", // chart title
"Time", // domain axis label
"Quantity", // range axis label
linedataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
CategoryPlot plot = chart.getCategoryPlot();
// customise the range axis...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setAutoRangeIncludesZero(true);
rangeAxis.setUpperMargin(1);
rangeAxis.setLabelAngle(Math.PI / 2.0);
return chart; }
//生成數據 public static DefaultCategoryDataset createDataset() {
DefaultCategoryDataset linedataset = new DefaultCategoryDataset();
// 各曲線名稱
String series1 = "car";
// 橫軸名稱(列名稱)
String type1 = "Jan";
String type2 = "Feb";
String type3 = "Mar";
linedataset.addValue(100, series1, type1); linedataset.addValue(200, series1, type2);
linedataset.addValue(300, series1, type3);
return linedataset; }
public static void saveAsFile(JFreeChart chart, String outputPath,
int weight, int height) {
FileOutputStream out = null;
try {
File outFile = new File(outputPath);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
out = new FileOutputStream(outputPath);
// 保存為PNG文件
ChartUtilities.writeChartAsPNG(out, chart, 600, 350);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// do nothing
}
}
}
}
}