我正在尝试使用JfreeChart创建XYLineChart。这是一张动态图表,我每隔2秒钟收到一次数据。我想使图表可滚动,以便我可以访问绘制的旧数据点。
我尝试将chartPanel添加到JScrollPane。不工作。它只能使整个窗口可滚动,而不是实际的图表。 有人能帮我吗?
我需要实时向后滚动才能看到之前绘制的点数。
这是我的代码:
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();
}
}
}