一个动态实时时序图的实现。
代码如下:
RealTimeChart.java
package com.media.zhb.jfreechart;
import java.awt.Font;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
public class RealTimeChart extends ChartPanel implements Runnable {
private static final long serialVersionUID = -2754150583683675881L;
private static TimeSeries timeSeries;
private long value = 0;
public RealTimeChart(String chartContent, String title, String yaxisName) {
super(createChart(chartContent, title, yaxisName));
}
private static JFreeChart createChart(String chartContent, String title,
String yaxisName) {
// 创建时序图对象
timeSeries = new TimeSeries(chartContent, Millisecond.class);
TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(
timeSeries);
JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title,
"时间(秒)", yaxisName, timeseriescollection, true, true, false);
// 设置标题字体
Font font = new Font("隶书", Font.BOLD, 25);
TextTitle textTitle = new TextTitle(title);
textTitle.setFont(font);
jfreechart.setTitle(textTitle);
// 设置图例字体
LegendTitle legend = jfreechart.getLegend(0);
legend.setItemFont(new Font("隶书", Font.TRUETYPE_FONT, 15));
XYPlot xyplot = jfreechart.getXYPlot();
// 纵坐标设定
ValueAxis valueaxis = xyplot.getDomainAxis();
// 自动设置数据轴数据范围
valueaxis.setAutoRange(true);
// 数据轴固定数据范围 30s
valueaxis.setFixedAutoRange(30000D);
valueaxis = xyplot.getRangeAxis();
// valueaxis.setRange(0.0D,200D);
// 纵轴
NumberAxis numAxis = (NumberAxis) xyplot.getRangeAxis();
// 设置纵轴标签字体
numAxis.setLabelFont(new Font("宋体", Font.BOLD, 14));
// 横轴
DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
// 设置横轴标签字体
dateaxis.setLabelFont(new Font("宋体", Font.BOLD, 14));
return jfreechart;
}
public void run() {
while (true) {
try {
timeSeries.add(new Millisecond(), randomNum());
Thread.sleep(300);
} catch (InterruptedException e) {
}
}
}
private long randomNum() {
System.out.println((Math.random() * 20 + 80));
return (long) (Math.random() * 20 + 80);
}
}
再写一个客户端代码。
TestClient.java
package com.media.zhb.jfreechart;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class TestClient {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Chart");
RealTimeChart rtcp = new RealTimeChart("随机数 ", "随机数", "数值");
frame.getContentPane().add(rtcp, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
(new Thread(rtcp)).start();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowevent) {
System.exit(0);
}
});
}
}