另壹種方式就是將實時類實現Runnable接口,在其run()方法中,通過無限循環將實時數據添加進TimeSeries,下面是較簡單的實現代碼:
java 代碼
//RealTimeChart .java
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
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 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);
XYPlot xyplot = jfreechart.getXYPlot();
//縱坐標設定
ValueAxis valueaxis = xyplot.getDomainAxis();
//自動設置數據軸數據範圍
valueaxis.setAutoRange(true);
//數據軸固定數據範圍 30s
valueaxis.setFixedAutoRange(30000D);
valueaxis = xyplot.getRangeAxis();
//valueaxis.setRange(0.0D,200D);
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);
}
}
//Test.java
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Test
{
/**
* @param args
*/
public static void main(String[] args)
{
JFrame frame=new JFrame("Test Chart");
RealTimeChart rtcp=new RealTimeChart("Random Data","隨機數","數值");
frame.getContentPane().add(rtcp,new BorderLayout().CENTER);
frame.pack();
frame.setVisible(true);
(new Thread(rtcp)).start();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent windowevent)
{
System.exit(0);
}
});
}
}
這兩中方法都有壹個問題,就是每實現壹個圖就要重新寫壹次,因為實時數據無法通過參數傳進來,在想有沒有可能通過setXXX()方式傳進實時數據,那樣的話就可以將實時曲線繪制類封裝起來,而只需傳遞些參數即可。