sleep(100)-Swing动态生成折线图

如何做一个实时动态Swing折线图呢?
由于脑海中构想了如下图这样一个画面,所以经过查资料写代码,实现了视觉化的图景。分享之。。。

sleep(100)-Swing动态生成折线图_第1张图片

public class JFSwingDynamicChart extends JFrame implements ActionListener {
	private TimeSeries series;
	private double lastValue = 100.0;
	
	/**
	 * 构造
	 */
	public JFSwingDynamicChart() {
		getContentPane().setBackground(Color.green);
	}

	/**
	 * 创建应用程序界面
	 */
	public void createUI() {
		this.series = new TimeSeries("Math.random()-随机数据", Millisecond.class);
		TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
		ChartPanel chartPanel = new ChartPanel(createChart(dataset));
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

		JPanel buttonPanel = new JPanel();
		buttonPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
		add(chartPanel);
		add(buttonPanel, BorderLayout.SOUTH);
	}

	/**
	 * 根据结果集构造JFreechart报表对象
	 * 
	 * @param dataset
	 * @return
	 */
	private JFreeChart createChart(XYDataset dataset) {
		JFreeChart result = ChartFactory.createTimeSeriesChart("Swing动态折线图", "系统当前时间",
				"动态数值变化", dataset, true, true, false);
		XYPlot plot = (XYPlot) result.getPlot();
		ValueAxis axis = plot.getDomainAxis();
		axis.setAutoRange(true);
		axis.setFixedAutoRange(60000.0);
		axis = plot.getRangeAxis();
		axis.setRange(0.0, 200.0);
		return result;
	}

	public void actionPerformed(ActionEvent e) {
	}

	/**
	 * 动态运行
	 */
	public void dynamicRun() {
		while (true) {
			double factor = 0.90 + 0.2 * Math.random();
			this.lastValue = this.lastValue * factor;
			Millisecond now = new Millisecond();
			this.series.add(new Millisecond(), this.lastValue);
			try {
				Thread.currentThread().sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	// 主函数入口
	public static void main(String[] args) {
		JFSwingDynamicChart jsdChart = new JFSwingDynamicChart();
		jsdChart.setTitle("Swing动态折线图");
		jsdChart.createUI();
		jsdChart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jsdChart.setBounds(100, 100, 900, 600);
		jsdChart.setVisible(true);
//		Color c=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)); 
		
		jsdChart.dynamicRun();
	}

}



-------------------------
Thread.currentThread().sleep(100); //线程交替,给绘制线程以时间可以解决此异常
Exception in thread "main" org.jfree.data.general.SeriesException: You are attempting to add an observation for the time period Wed Jul 07 11:36:28 CST 2010 but the series already contains an observation for that time period. Duplicates are not permitted.  Try using the addOrUpdate() method.
	at org.jfree.data.time.TimeSeries.add(TimeSeries.java:529)
	at org.jfree.data.time.TimeSeries.add(TimeSeries.java:572)
	at org.jfree.data.time.TimeSeries.add(TimeSeries.java:558)
	at chapter09.JFSwingDynamicChart.dynamicRun(JFSwingDynamicChart.java:76)
	at chapter09.JFSwingDynamicChart.main(JFSwingDynamicChart.java:96)

你可能感兴趣的:(java,thread,swing,jfreechart)