绘制开始时间的实时图表
这是基于@ trashgod关于实时绘图的示例的代码:
import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; 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.plot.XYPlot; import org.jfree.data.time.DynamicTimeSeriesCollection; import org.jfree.data.time.Second; /** * @see https://stackoverflow.com/a/21307289/230513 */ public class DynamicTimeSeriesChart extends JPanel { private static final long serialVersionUID = 5128935838291298041L; private final DynamicTimeSeriesCollection dataset; private final JFreeChart chart; public DynamicTimeSeriesChart(final String title) { dataset = new DynamicTimeSeriesCollection(1, 1000, new Second()); dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2014)); dataset.addSeries(new float[1], 0, title); chart = ChartFactory.createTimeSeriesChart( title, "Time", title, dataset, true, true, false); final XYPlot plot = chart.getXYPlot(); DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setFixedAutoRange(10000); axis.setDateFormatOverride(new SimpleDateFormat("ss.SS")); final ChartPanel chartPanel = new ChartPanel(chart); add(chartPanel); } public void update(float value) { float[] newData = new float[1]; newData[0] = value; dataset.advanceTime(); dataset.appendData(newData); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final DynamicTimeSeriesChart chart = new DynamicTimeSeriesChart("Alternating data"); frame.add(chart); frame.pack(); Timer timer = new Timer(1000, new ActionListener() { private boolean b; @Override public void actionPerformed(ActionEvent e) { chart.update(b ? 1 : 0); b = !b; } }); timer.start(); frame.setVisible(true); } }); } }
在运行Java之后,我仍然不明白为什么图表从40秒开始,尽管new Seconds
从0开始? 通过代码; 找不到任何设置在40秒开始。
此外,如何向后滚动图表以查看以前的数据。
该图在用于构造传递给setTimeBase()
的Second
的日期的午夜后16分40秒开始。 这是在nMoments
构造函数参数中指定的相同的1000个间隔,每个间隔长nMoments
。 在时间设置为午夜的情况下,获得基于零的显示的一些可能的替代方案。
-
使
nMoments
为60
的倍数。dataset = new DynamicTimeSeriesCollection(1, 960, new Second()); dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2014));
-
从名义基准日期中减去
nMoments
。int nMoments = 1000; dataset = new DynamicTimeSeriesCollection(1, nMoments, new Second()); Calendar c = Calendar.getInstance(); c.setTime(new Date(0)); c.add(Calendar.SECOND, -nMoments); dataset.setTimeBase(new Second(c.getTime()));
两种方法都产生相同的显示。