Jfreechart make a dynamic scrollable chart

174 views Asked by At

I am trying to create a XYLineChart using JfreeChart. It is a dynamic chart and I receive data every 2 seconds upto a minute. I want to make the chart scrollable so that I can visit the older data points plotted.

I tried adding the chartPanel to a JScrollPane. Did not work. It only makes the entire window scrollable, but not the actual chart. Can someone help me?

I need to scroll back real time in order to see the previously plotted points.

Here's my code:

class DynamicData extends JFrame {
private TimeSeries series;
private TimeSeries series2;
public DynamicData(String title) {
    super(title);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.series = new TimeSeries("Time", Millisecond.class);
    this.series2 = new TimeSeries("Time", Millisecond.class);
    final TimeSeriesCollection dataset = new     TimeSeriesCollection(this.series);
    DateAxis domainAxis = new DateAxis("Time");
    NumberAxis rangeAxis = new NumberAxis("Packet Size");
    XYBarRenderer renderer = new XYBarRenderer(0.1);

    Day d1 = new Day();
    domainAxis.setAutoRange(true);
    //domainAxis.setRange(new DateRange(d1.getFirstMillisecond(), d1.getLastMillisecond()));

    XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

    mainPlot.setDomainGridlinesVisible(true);
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    JFreeChart chart = new JFreeChart(null, null, mainPlot, true);
    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(600, 600));

    this.add(chartPanel);
    this.add(getScrollBar(domainAxis), BorderLayout.SOUTH);
    this.pack();
 }


 private JScrollBar getScrollBar(final DateAxis domainAxis){
    final double r1 = domainAxis.getLowerBound();
    final double r2 = domainAxis.getUpperBound();
    JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 100, 0, 400);
    scrollBar.addAdjustmentListener( new AdjustmentListener() {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            double x = e.getValue();
            domainAxis.setRange(r1+x, r2+x);
        }
    });
    return scrollBar;
}
public void plotGraph(long value) 
{
     try
    {
        this.series.addOrUpdate(new Millisecond(), value);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    } 
}
}
0

There are 0 answers