Dynamic Chart using JFreeChart

浪尽此生 提交于 2019-11-29 17:54:34

You need to have a thread where all this data is coming from. For example from your backend. Then, every time there is a new set of data for the chart you will need to update the chart via the Event Dispatch Thread. If your chart data is coming in regular intervals it is fairly easy (ie. pull), however if it is push (ie. the data is more random), and can get a little more tricky.

Remove all the GUI creation out of the plot method :

JFreeChart chart = new JFreeChart("Adaptive Filter", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
panel = new ChartPanel(chart, true, true, true, false, true);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(750, 500);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);

This only needs to be called once. The plot method will be called every time new data comes.

Here is a simple approach :

public void startCharting() {

    final MySoundCard card = new MySoundCard();
    final MyJFreeChart chart = new MyJFreeChart();

    Runnable r = new Runnable() {

        @Override
        public void run() {
            while(true) {

                int[] i = card.FileR();


                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {

                        chart.plot();
                    }

                });


                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    };

    Thread t = new Thread(r);
    t.start();
}

A thread calls your datasource every second and then updates the chart. The updates are invoked in the Event Dispatch Thread.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!