在这里主要贴上JFreeChart做的两个小例子,分别是柱状图和动态显示JVM内存状况图。
先说明一下jfreechart的概念,jfreechart工具基本上把一个图形分成了几个逻辑部分:
1.首先是整个的画布对象(chart),画布就相当与一个大的容器,包含一些图形元素,比如为一张白纸
2.然后是画图区域对象(plot),就是实际图形所占据的区域,比如为白纸上的一个长方形
3.然后是图形所需要两条轴对象(axis),比如为白纸上的两条轴线
4.最后是如何进行图像的绘制对象(render),比如为一只画图的笔
5.除开上面的这些对象,还有一个最主要的就是通过必须的数据集(dataset)来生成图形了
好了,其它的API就看文档了。现在开始说开发JFreeChart例子的步骤:
1. 首先下载jfreechart包。
2. 接着用MyEclipse创建一个Java Project.
3. 引用包, 要加入的包是gnujaxp.jar, jfreechart-1.0.12.jar, jcommon-1.0.15.jar
这样就把开发环境配好了,接下来就是创建类文件。先从柱状图开始.
1 import java.io.FileOutputStream;
2
3 import org.jfree.chart.ChartFactory;
4 import org.jfree.chart.ChartUtilities;
5 import org.jfree.chart.JFreeChart;
6 import org.jfree.chart.plot.PlotOrientation;
7 import org.jfree.data.category.CategoryDataset;
8 import org.jfree.data.category.DefaultCategoryDataset;
9
10 public class BarChartDemo {
11 private static String rowKeys[] ={"Apple", "Banana", "Watermelon"};
12 private static String columnKeys[] ={"Guangzhou", "Shanghai", "Beijing"};
13 private static String rowKeys_zh_CN[] ={"苹果", "香蕉", "西瓜"};
14 private static String columnKeys_zh_CN[] ={"广州", "上海", "北京"};
15 /**
16 * @param args
17 */
18 public static void main(String[] args) {
19 CategoryDataset dataSet = getComplexDataSet();
20 JFreeChart chart = ChartFactory.createBarChart("Fruit Output Chart",// 图表标题
21 "Fruit",// 目录轴的显示标签
22 "Output",// 数值轴的显示标签
23 dataSet,// 数据集
24 PlotOrientation.VERTICAL,// 图表方向:水平、垂直
25 true,// 是否显示图例(对于简单的柱状图必须是false)
26 false,// 是否生成工具
27 false// 是否生成URL链接
28 );
29 FileOutputStream fosJPG = null;
30 try {
31 fosJPG = new FileOutputStream("D:\\fruit.jpg");
32 ChartUtilities.writeChartAsJPEG(fosJPG, chart, 400, 300);
33 } catch (Exception e) {
34 e.printStackTrace();
35 } finally {
36 try {
37 fosJPG.close();
38 } catch (Exception e) {
39 e.printStackTrace();
40 }
41 }
42 }
43
44 /**
45 * 获取一个演示用的简单数据集对象
46 *
47 * @return
48 */
49 private static CategoryDataset getDataSet() {
50 DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();
51 categoryDataset.addValue(100, "", rowKeys[0]);
52 categoryDataset.addValue(200, "", rowKeys[1]);
53 categoryDataset.addValue(300, "", rowKeys[2]);
54 return categoryDataset;
55 }
56
57 /**
58 * 获取一个演示用的组合数据集对象
59 *
60 * @return
61 */
62 private static CategoryDataset getComplexDataSet() {
63 DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();
64 categoryDataset.addValue(100, columnKeys[0], rowKeys[0]);
65 categoryDataset.addValue(110, columnKeys[1], rowKeys[0]);
66 categoryDataset.addValue(120, columnKeys[2], rowKeys[0]);
67 categoryDataset.addValue(200, columnKeys[0], rowKeys[1]);
68 categoryDataset.addValue(210, columnKeys[1], rowKeys[1]);
69 categoryDataset.addValue(220, columnKeys[2], rowKeys[1]);
70 categoryDataset.addValue(300, columnKeys[0], rowKeys[2]);
71 categoryDataset.addValue(310, columnKeys[1], rowKeys[2]);
72 categoryDataset.addValue(320, columnKeys[2], rowKeys[2]);
73 return categoryDataset;
74 }
75 }
76
运行后,可看到结果了。
接着下来是动态显示JVM内存状况图的原码.
1 import java.awt.BasicStroke;
2 import java.awt.BorderLayout;
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7 import java.awt.event.WindowAdapter;
8 import java.awt.event.WindowEvent;
9
10 import javax.swing.BorderFactory;
11 import javax.swing.JFrame;
12 import javax.swing.JPanel;
13 import javax.swing.Timer;
14
15 import org.jfree.chart.ChartPanel;
16 import org.jfree.chart.JFreeChart;
17 import org.jfree.chart.axis.DateAxis;
18 import org.jfree.chart.axis.NumberAxis;
19 import org.jfree.chart.plot.XYPlot;
20 import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
21 import org.jfree.data.time.Millisecond;
22 import org.jfree.data.time.TimeSeries;
23 import org.jfree.data.time.TimeSeriesCollection;
24 import org.jfree.ui.RectangleInsets;
25
26 public class MemoryUsage extends JPanel {
27
28 class DataGenerator extends Timer implements ActionListener {
29
30 /*
31 * Invoked when an action occurs.
32 *
33 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
34 */
35 public void actionPerformed(ActionEvent actionevent) {
36 long free = Runtime.getRuntime().freeMemory();
37 long total = Runtime.getRuntime().totalMemory();
38 addTotalObservation(total);
39 addFreeObservation(free);
40 }
41
42 DataGenerator(int i) {
43 super(i, null);
44 addActionListener(this);
45 }
46 }
47
48 public MemoryUsage(int maxItemAge) {
49 super(new BorderLayout());
50 total = new TimeSeries("Total Memory",
51 org.jfree.data.time.Millisecond.class);
52 total.setMaximumItemAge(maxItemAge);
53 free = new TimeSeries("Free Memory",
54 org.jfree.data.time.Millisecond.class);
55 free.setMaximumItemAge(maxItemAge);
56
57 TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
58 timeseriescollection.addSeries(total);
59 timeseriescollection.addSeries(free);
60
61 DateAxis dateaxis = new DateAxis("Time");
62 NumberAxis numberaxis = new NumberAxis("Memory");
63 dateaxis.setTickLabelFont(new Font("SansSerif", 0, 12));
64 numberaxis.setTickLabelFont(new Font("SansSerif", 0, 12));
65 dateaxis.setLabelFont(new Font("SansSerif", 0, 14));
66 numberaxis.setLabelFont(new Font("SansSerif", 0, 14));
67 dateaxis.setAutoRange(true);
68 dateaxis.setLowerMargin(0.0D);
69 dateaxis.setUpperMargin(0.0D);
70 dateaxis.setTickLabelsVisible(true);
71 numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
72
73 XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer(
74 true, false);
75 xylineandshaperenderer.setSeriesPaint(0, Color.RED); // 改变第一个Series的颜色
76 xylineandshaperenderer.setSeriesPaint(1, Color.YELLOW);// 改变第二个Series的颜色
77 xylineandshaperenderer.setSeriesStroke(0, new BasicStroke(1F, 0, 2));
78 xylineandshaperenderer.setSeriesStroke(1, new BasicStroke(1F, 0, 2));
79
80 XYPlot xyplot = new XYPlot(timeseriescollection, dateaxis, numberaxis,
81 xylineandshaperenderer);
82 xyplot.setBackgroundPaint(Color.BLACK); // 改变背景颜色
83 xyplot.setDomainGridlinePaint(Color.white);
84 xyplot.setRangeGridlinePaint(Color.white);
85 xyplot.setAxisOffset(new RectangleInsets(1D, 1D, 1D, 1D));
86
87 JFreeChart jfreechart = new JFreeChart("JVM Memory Usage", new Font(
88 "SansSerif", 1, 24), xyplot, true);
89 jfreechart.setBackgroundPaint(Color.white);
90
91 ChartPanel chartpanel = new ChartPanel(jfreechart, true);
92 chartpanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory
93 .createEmptyBorder(10, 10, 10, 10), BorderFactory
94 .createLineBorder(Color.black)));
95
96 add(chartpanel);
97 }
98
99 private void addTotalObservation(double d) {
100 total.add(new Millisecond(), d);
101 }
102
103 private void addFreeObservation(double d) {
104 free.add(new Millisecond(), d);
105 }
106
107 /**
108 * @param args
109 */
110 public static void main(String[] args) {
111 JFrame jframe = new JFrame("JVM Memory Usage");
112 MemoryUsage memoryusagedemo = new MemoryUsage(10000);
113 jframe.getContentPane().add(memoryusagedemo, "Center");
114 jframe.setBounds(200, 120, 1000, 500);
115 jframe.setVisible(true);
116 (memoryusagedemo.new DataGenerator(1000)).start();
117 jframe.addWindowListener(new WindowAdapter() {
118 public void windowClosing(WindowEvent windowevent) {
119 System.exit(0);
120 }
121 });
122 }
123
124 private TimeSeries total;
125 private TimeSeries free;
126 }
127
祝你好运。