分类: Java
2008-04-04 20:41:37
Event notification(jfreechart动态图的实现机制) JFreeChart uses an event notification mechanism that allows it to respond to changes to any component of the chart. For example, whenever a dataset is updated, a DatasetChangeEvent is sent to all listeners that are registered with the dataset. This triggers the following sequence of events: • the plot (which registers itself with the dataset as a DatasetChangeListener) receives notification of the dataset change. It updates the axis ranges (if necessary) then passes on a PlotChangeEvent to all its registered listeners; • the chart receives notification of the plot change event, and passes on a ChartChangeEvent to all its registered listeners; • finally, for charts that are displayed in a ChartPanel, the panel will receive the chart change event.It responds by redrawing the chart—a complete redraw, not just the updated data. Performance(性能) JFreeChart wasnt designed specifically for generating real-time charts. Each time a dataset is updated, the ChartPanel reacts by redrawing the entire chart. Creating the Dataset The dataset is created using two TimeSeries objects(one for the total memory and the other for the free memory) that are added to a single time seriescollection: // create two series that automatically discard data > 30 seconds old... this.total = new TimeSeries("Total", Millisecond.class); this.total.setMaximumItemAge(30000); this.free = new TimeSeries("Free", Millisecond.class); this.free.setMaximumItemAge(30000); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(this.total); dataset.addSeries(this.free); Updating the Dataset In the demo, the dataset is updated by adding data to the two time series from a separate thread,managed by the following timer: class DataGenerator extends Timer implements ActionListener { DataGenerator(int interval) { super(interval, null); addActionListener(this); } public void actionPerformed(ActionEvent event) { long f = Runtime.getRuntime().freeMemory(); long t = Runtime.getRuntime().totalMemory(); addTotalObservation(t); addFreeObservation(f); } } jfreechart在更新数据和chart重绘并没有实现同步,因此以上代码可能会存在安全隐患: Note that JFreeChart does not yet use thread synchronisation between the chart drawing code and the dataset update code, so this approach is a little unsafe.
|